Стайлгайд PEP8
PEP8 – это стайлгайд написания кода на Питоне. Он является частью Питона. Его все соблюдают.
Он отвечает на вопросы в таком духе,
- Табы или пробелы?
- Какая максимальная длина строки?
- Одинарные или двойные кавычки?
- Где ставить пробелы, а где — нет?
- Сколько ставить пустых строк?
- Как импортировать?
- Какой стиль именования сущностей?
Лучше прочитать оригинал документа PEP8 (если не осилишь – вот куцый перевод на русский). Особое внимание – к секции “A Foolish Consistency is the Hobgoblin of Little Minds”.
PEP 8 – закон. Его надо соблюдать. Если в вашей программе много нарушений PEP 8 – она выглядит неряшливо, по-дилетантски.
Помимо PEP 8 есть ещё pep8 . pep8 – это модуль, позволяющий проверять, соответствует ли код стандарту PEP 8. Сперва её надо установить ( pip install pep8 ), поле этого запустить, указав путь до файла или папки с кодом: pep8 ./2_wallie_how_are_you/wallie.py . Программа выдаст все нарушения PEP 8. Остаётся их только поправить.
Попробуйте бесплатные уроки по Python
Получите крутое код-ревью от практикующих программистов с разбором ошибок и рекомендациями, на что обратить внимание — бесплатно.
Переходите на страницу учебных модулей «Девмана» и выбирайте тему.
PEP 8: что это такое и как применять
PEP 8, иногда обозначаемый PEP8 или PEP-8, представляет собой документ, содержащий рекомендации по написанию кода на Python. Он был составлен в 2001 году Гвидо ван Россумом, Барри Варшавой и Ником Когланом. Основная цель PEP 8 – улучшить читабельность и логичность кода на Python.
PEP расшифровывается как Python Enhancement Proposal («Предложение по усовершенствованию Python»), и их несколько. PEP — это документ для сообщества, который описывает новые функции, предлагаемые для Python, и содержит такие аспекты языка, как дизайн и стиль.
В цикле из трех статей мы разберем основные принципы, изложенные в PEP 8. Эти статьи предназначены для новичков и программистов среднего уровня, поэтому мы не будем затрагивать некоторые из наиболее сложных тем. Вы можете изучить их самостоятельно, прочитав полную документацию по PEP 8 .
Из данной серии статей вы узнаете:
- как писать Python-код, соответствующий PEP8;
- какие доводы лежат в основе рекомендаций, изложенных в PEP8;
- как настроить среду разработки так, чтобы вы могли начать писать код на Python по PEP8.
Зачем нужен PEP 8
“Читаемость имеет значение”, — Дзен Python
PEP 8 существует для улучшения читаемости кода Python. Но почему так важна удобочитаемость? Почему написание читаемого кода является одним из руководящих принципов языка Python?
Как сказал Гвидо ван Россум: «Код читают гораздо чаще, чем пишут». Вы можете потратить несколько минут или целый день на написание фрагмента кода для аутентификации пользователя. В дальнейшем вам не придётся его писать. Но перечитывать его вы точно будете. Этот фрагмент кода может остаться частью проекта, над которым вы работаете. Каждый раз, возвращаясь к этому файлу, вам нужно будет вспомнить, что делает этот код и зачем вы его написали. Поэтому удобочитаемость имеет большое значение.
Если вы новичок в Python, возможно, вам уже через несколько дней или недель будет трудно вспомнить, что делает фрагмент кода. Но если вы следуете PEP 8, вы можете быть уверены, что правильно назвали свои переменные . Вы будете знать, что добавили достаточно пробелов, чтобы обособить логические шаги. Вы также снабдили свой код отличными комментариями. Все это сделает ваш код будет более читабельным, а значит, к нему будет легче вернуться. Следование правилам PEP 8 для новичка может сделать изучение Python гораздо более приятной задачей.
Следование PEP 8 особенно важно, если вы претендуете на должность разработчика. Написание понятного, читаемого кода свидетельствует о профессионализме. Это скажет работодателю, что вы понимаете, как правильно структурировать свой код.
Работая над проектами, вам, скорее всего, придется сотрудничать с другими программистами. Здесь, опять же, очень важно писать читаемый код. Другие люди, которые, возможно, никогда раньше не встречали вас и не видели ваш стиль программирования, должны будут прочитать и понять ваш код. Наличие руководящих принципов, которым вы следуете и которые знаете, облегчит другим чтение вашего кода.
Когда стоит игнорировать PEP 8
Краткий ответ на этот вопрос – никогда. Если вы строго следуете PEP 8, то можете гарантировать, что у вас будет чистый, профессиональный и читабельный код. Это принесет пользу вам, а также сотрудникам и потенциальным работодателям.
Однако некоторые рекомендации в PEP 8 неудобны в следующих случаях:
- соблюдение PEP 8 нарушает совместимость с существующим программным обеспечением
- код, связанный с тем, над чем вы работаете, несовместим с PEP 8
- код должен оставаться совместимым со старыми версиями Python
Как проверить соответствие кода PEP 8
Чтобы убедиться, что ваш код соответствует PEP 8, необходимо многое проверить. Помнить все эти правила при разработке кода может быть непросто. Особенно много времени уходит на приведение прошлых проектов к стандарту PEP 8. К счастью, есть инструменты, которые помогут ускорить этот процесс.
Существует два класса инструментов, которые можно использовать для обеспечения соответствия PEP 8: линтеры и автоформаттеры.
Линтеры
Линтеры – это программы, которые анализируют код, помечают ошибки и предлагают способы их исправления. Они особенно полезны как расширения редактора, поскольку выявляют ошибки и стилистические проблемы во время написания кода.
Вот пара лучших линтеров для кода на Python:
pycodestyle
Это инструмент для проверки вашего кода на соответствие некоторым стилевым соглашениям в PEP8.
Установите pycodestyle с помощью pip:
$ pip install pycodestyle
Вы можете запустить pycodestyle из терминала, используя следующую команду:
$ pycodestyle code.py
code.py:1:17: E231 missing whitespace after ',' code.py:2:21: E231 missing whitespace after ',' code.py:6:19: E711 comparison to None should be 'if cond is None:'
flake8
Это инструмент, который сочетает в себе отладчик, pyflakes и pycodestyle.
Установите flake8 с помощью pip:
$ pip install flake8
Запустите flake8 из терминала, используя следующую команду:
$ flake8 code.py
code.py:1:17: E231 missing whitespace after ',' code.py:2:21: E231 missing whitespace after ',' code.py:3:17: E999 SyntaxError: invalid syntax code.py:6:19: E711 comparison to None should be 'if cond is None:'
Замечание: Дополнительная строка в выводе указывает на синтаксическую ошибку.
Автоформаттеры
Автоформаттеры – это программы, которые автоматически реорганизуют ваш код для соответствия PEP 8. Одна из таких программ — black . Она автоматически форматирует код для приведения его в соответствие с большинством правил PEP 8. Единственное, она ограничивает длину строки до 88 символов, а не до 79, как рекомендовано стандартом. Однако вы можете изменить это, добавив флаг командной строки, как в примере ниже.
Установите black с помощью pip. Для запуска требуется Python 3.6+:
$ pip install black
Его можно запустить из командной строки, как и в случае с линтерами. Допустим, вы начали со следующего кода, который не соответствует PEP 8, в файле с именем code.py:
for i in range(0,3): for j in range(0,3): if (i==2): print(i,j)
Затем вы можете запустить следующую команду через командную строку:
$ black code.py reformatted code.py All done! ✨ ? ✨
code.py будет автоматически приведён к следующему виду:
for i in range(0, 3): for j in range(0, 3): if i == 2: print(i, j)
Если вы хотите изменить ограничение длины строки, можно использовать флаг —line-length :
$ black --line-length=79 code.py reformatted code.py All done! ✨ ? ✨
Работа двух других автоформаттеров – autopep8 и yapf – аналогична работе black .
О том, как использовать эти инструменты, хорошо написано в статье Python Code Quality: Tools & Best Practices Александра ван Тол.
В следующих статьях цикла про PEP 8 читайте:
- Нейминг и размещение кода
- Комментарии, пробелы, выбор методов
PEP 1 – PEP Purpose and Guidelines
PEP stands for Python Enhancement Proposal. A PEP is a design document providing information to the Python community, or describing a new feature for Python or its processes or environment. The PEP should provide a concise technical specification of the feature and a rationale for the feature.
We intend PEPs to be the primary mechanisms for proposing major new features, for collecting community input on an issue, and for documenting the design decisions that have gone into Python. The PEP author is responsible for building consensus within the community and documenting dissenting opinions.
Because the PEPs are maintained as text files in a versioned repository, their revision history is the historical record of the feature proposal. This historical record is available by the normal git commands for retrieving older revisions, and can also be browsed on GitHub.
PEP Audience
The typical primary audience for PEPs are the core developers of the CPython reference interpreter and their elected Steering Council, as well as developers of other implementations of the Python language specification.
However, other parts of the Python community may also choose to use the process (particularly for Informational PEPs) to document expected API conventions and to manage complex design coordination problems that require collaboration across multiple projects.
PEP Types
There are three kinds of PEP:
- A Standards Track PEP describes a new feature or implementation for Python. It may also describe an interoperability standard that will be supported outside the standard library for current Python versions before a subsequent PEP adds standard library support in a future version.
- An Informational PEP describes a Python design issue, or provides general guidelines or information to the Python community, but does not propose a new feature. Informational PEPs do not necessarily represent a Python community consensus or recommendation, so users and implementers are free to ignore Informational PEPs or follow their advice.
- A Process PEP describes a process surrounding Python, or proposes a change to (or an event in) a process. Process PEPs are like Standards Track PEPs but apply to areas other than the Python language itself. They may propose an implementation, but not to Python’s codebase; they often require community consensus; unlike Informational PEPs, they are more than recommendations, and users are typically not free to ignore them. Examples include procedures, guidelines, changes to the decision-making process, and changes to the tools or environment used in Python development. Any meta-PEP is also considered a Process PEP.
PEP Workflow
Python’s Steering Council
There are several references in this PEP to the “Steering Council” or “Council”. This refers to the current members of the elected Steering Council described in PEP 13, in their role as the final authorities on whether or not PEPs will be accepted or rejected.
Python’s Core Developers
There are several references in this PEP to “core developers”. This refers to the currently active Python core team members described in PEP 13.
Python’s BDFL
Previous versions of this PEP used the title “BDFL-Delegate” for PEP decision makers. This was a historical reference to Python’s previous governance model, where all design authority ultimately derived from Guido van Rossum, the original creator of the Python programming language. By contrast, the Steering Council’s design authority derives from their election by the currently active core developers. Now, PEP-Delegate is used in place of BDFL-Delegate.
PEP Editors
The PEP editors are individuals responsible for managing the administrative and editorial aspects of the PEP workflow (e.g. assigning PEP numbers and changing their status). See PEP Editor Responsibilities & Workflow for details.
PEP editorship is by invitation of the current editors, and they can be contacted by mentioning @python/pep-editors on GitHub. All of the PEP workflow can be conducted via the GitHub PEP repository issues and pull requests.
Start with an idea for Python
The PEP process begins with a new idea for Python. It is highly recommended that a single PEP contain a single key proposal or new idea; the more focused the PEP, the more successful it tends to be. Most enhancements and bug fixes don’t need a PEP and can be submitted directly to the Python issue tracker. The PEP editors reserve the right to reject PEP proposals if they appear too unfocused or too broad. If in doubt, split your PEP into several well-focused ones.
Each PEP must have a champion – someone who writes the PEP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The PEP champion (a.k.a. Author) should first attempt to ascertain whether the idea is PEP-able. Posting to the Ideas category of the Python Discourse is usually the best way to go about this, unless a more specialized venue is appropriate, such as the Typing category (for static typing ideas) or Packaging category (for packaging ideas) on the Python Discourse.
Vetting an idea publicly before going as far as writing a PEP is meant to save the potential author time. Many ideas have been brought forward for changing Python that have been rejected for various reasons. Asking the Python community first if an idea is original helps prevent too much time being spent on something that is guaranteed to be rejected based on prior discussions (searching the internet does not always do the trick). It also helps to make sure the idea is applicable to the entire community and not just the author. Just because an idea sounds good to the author does not mean it will work for most people in most areas where Python is used.
Once the champion has asked the Python community as to whether an idea has any chance of acceptance, a draft PEP should be presented to the appropriate venue mentioned above. This gives the author a chance to flesh out the draft PEP to make properly formatted, of high quality, and to address initial concerns about the proposal.
Submitting a PEP
Following the above initial discussion, the workflow varies based on whether any of the PEP’s co-authors are core developers. If one or more of the PEP’s co-authors are core developers, they are responsible for following the process outlined below. Otherwise (i.e. none of the co-authors are core developers), then the PEP author(s) will need to find a sponsor for the PEP.
Ideally, a core developer sponsor is identified, but non-core sponsors may also be selected with the approval of the Steering Council. Members of the GitHub “PEP editors” team are pre-approved to be sponsors. The sponsor’s job is to provide guidance to the PEP author to help them through the logistics of the PEP process (somewhat acting like a mentor). Being a sponsor does not disqualify that person from becoming a co-author or PEP-Delegate later on (but not both). The sponsor of a PEP is recorded in the “Sponsor:” field of the header.
Once the sponsor or the core developer(s) co-authoring the PEP deem the PEP ready for submission, the proposal should be submitted as a draft PEP via a GitHub pull request. The draft must be written in PEP style as described below, else it will fail review immediately (although minor errors may be corrected by the editors).
The standard PEP workflow is:
- You, the PEP author, fork the PEP repository, and create a file named pep- NNNN .rst that contains your new PEP. NNNN should be the next available PEP number not used by a published or in-PR PEP.
- In the “PEP:” header field, enter the PEP number that matches your filename as your draft PEP number.
- In the “Type:” header field, enter “Standards Track”, “Informational”, or “Process” as appropriate, and for the “Status:” field enter “Draft”. For full details, see PEP Header Preamble.
- Update .github/CODEOWNERS such that any co-author(s) or sponsors with write access to the PEP repository are listed for your new file. This ensures any future pull requests changing the file will be assigned to them.
- Push this to your GitHub fork and submit a pull request.
- The PEP editors review your PR for structure, formatting, and other errors. For a reST-formatted PEP, PEP 12 is provided as a template. It also provides a complete introduction to reST markup that is used in PEPs. Approval criteria are:
- It is sound and complete. The ideas must make technical sense. The editors do not consider whether they seem likely to be accepted.
- The title accurately describes the content.
- The PEP’s language (spelling, grammar, sentence structure, etc.) and code style (examples should match PEP 7 & PEP 8) should be correct and conformant. The PEP text will be automatically checked for correct reStructuredText formatting when the pull request is submitted. PEPs with invalid reST markup will not be approved.
Editors are generally quite lenient about this initial review, expecting that problems will be corrected by the reviewing process. Note: Approval of the PEP is no guarantee that there are no embarrassing mistakes! Correctness is the responsibility of authors and reviewers, not the editors.
If the PEP isn’t ready for approval, an editor will send it back to the author for revision, with specific instructions.
Once the review process is complete, and the PEP editors approve it (note that this is not the same as accepting your PEP!), they will squash commit your pull request onto main.
The PEP editors will not unreasonably deny publication of a PEP. Reasons for denying PEP status include duplication of effort, being technically unsound, not providing proper motivation or addressing backwards compatibility, or not in keeping with the Python philosophy. The Steering Council can be consulted during the approval phase, and are the final arbiter of a draft’s PEP-ability.
Developers with write access to the PEP repository may claim PEP numbers directly by creating and committing a new PEP. When doing so, the developer must handle the tasks that would normally be taken care of by the PEP editors (see PEP Editor Responsibilities & Workflow). This includes ensuring the initial version meets the expected standards for submitting a PEP. Alternately, even developers should submit PEPs via pull request. When doing so, you are generally expected to handle the process yourself; if you need assistance from PEP editors, mention @python/pep-editors on GitHub.
As updates are necessary, the PEP author can check in new versions if they (or a collaborating developer) have write access to the PEP repository. Getting a PEP number assigned early can be useful for ease of reference, especially when multiple draft PEPs are being considered at the same time.
Standards Track PEPs consist of two parts, a design document and a reference implementation. It is generally recommended that at least a prototype implementation be co-developed with the PEP, as ideas that sound good in principle sometimes turn out to be impractical when subjected to the test of implementation.
Discussing a PEP
As soon as a PEP number has been assigned and the draft PEP is committed to the PEP repository, a discussion thread for the PEP should be created to provide a central place to discuss and review its contents, and the PEP should be updated so that the Discussions-To header links to it.
The PEP authors (or sponsor, if applicable) may select any reasonable venue for the discussion, so long as the the following criteria are met:
- The forum is appropriate to the PEP’s topic.
- The thread is publicly available on the web so that all interested parties can participate.
- The discussion is subject to the Python Community Code of Conduct.
- A direct link to the current discussion thread is provided in the PEP under the Discussions-To header.
The PEPs category of the Python Discourse is the preferred choice for most new PEPs, whereas historically the Python-Dev mailing list was commonly used. Some specialized topics have specific venues, such as the Typing category and the Packaging category on the Python Discourse for typing and packaging PEPs, respectively. If the PEP authors are unsure of the best venue, the PEP Sponsor and PEP editors can advise them accordingly.
If a PEP undergoes a significant re-write or other major, substantive changes to its proposed specification, a new thread should typically be created in the chosen venue to solicit additional feedback. If this occurs, the Discussions-To link must be updated and a new Post-History entry added pointing to this new thread.
If it is not chosen as the discussion venue, a brief announcement post should be made to the PEPs category with at least a link to the rendered PEP and the Discussions-To thread when the draft PEP is committed to the repository and if a major-enough change is made to trigger a new thread.
PEP authors are responsible for collecting community feedback on a PEP before submitting it for review. However, to avoid long-winded and open-ended discussions, strategies such as soliciting private or more narrowly-tailored feedback in the early design phase, collaborating with other community members with expertise in the PEP’s subject matter, and picking an appropriately-specialized discussion for the PEP’s topic (if applicable) should be considered. PEP authors should use their discretion here.
Once the PEP is assigned a number and committed to the PEP repository, substantive issues should generally be discussed on the canonical public thread, as opposed to private channels, GitHub pull request reviews or unrelated venues. This ensures everyone can follow and contribute, avoids fragmenting the discussion, and makes sure it is fully considered as part of the PEP review process. Comments, support, concerns and other feedback on this designated thread are a critical part of what the Steering Council or PEP-Delegate will consider when reviewing the PEP.
PEP Review & Resolution
Once the authors have completed a PEP, they may request a review for style and consistency from the PEP editors. However, content review and acceptance of the PEP is ultimately the responsibility of the Steering Council, which is formally initiated by opening a Steering Council issue once the authors (and sponsor, if any) determine the PEP is ready for final review and resolution.
To expedite the process in selected cases (e.g. when a change is clearly beneficial and ready to be accepted, but the PEP hasn’t been formally submitted for review yet), the Steering Council may also initiate a PEP review, first notifying the PEP author(s) and giving them a chance to make revisions.
The final authority for PEP approval is the Steering Council. However, whenever a new PEP is put forward, any core developer who believes they are suitably experienced to make the final decision on that PEP may offer to serve as its PEP-Delegate by notifying the Steering Council of their intent. If the Steering Council approves their offer, the PEP-Delegate will then have the authority to approve or reject that PEP.
The term “PEP-Delegate” is used under the Steering Council governance model for the PEP’s designated decision maker, who is recorded in the “PEP-Delegate” field in the PEP’s header. The term “BDFL-Delegate” is a deprecated alias for PEP-Delegate, a legacy of the time when when Python was led by a BDFL. Any legacy references to “BDFL-Delegate” should be treated as equivalent to “PEP-Delegate”.
An individual offering to nominate themselves as a PEP-Delegate must notify the relevant authors and (when present) the sponsor for the PEP, and submit their request to the Steering Council (which can be done via a new issue ). Those taking on this responsibility are free to seek additional guidance from the Steering Council at any time, and are also expected to take the advice and perspectives of other core developers into account.
The Steering Council will generally approve such self-nominations by default, but may choose to decline them. Possible reasons for the Steering Council declining a self-nomination as PEP-Delegate include, but are not limited to, perceptions of a potential conflict of interest (e.g. working for the same organisation as the PEP submitter), or simply considering another potential PEP-Delegate to be more appropriate. If core developers (or other community members) have concerns regarding the suitability of a PEP-Delegate for any given PEP, they may ask the Steering Council to review the delegation.
If no volunteer steps forward, then the Steering Council will approach core developers (and potentially other Python community members) with relevant expertise, in an attempt to identify a candidate that is willing to serve as PEP-Delegate for that PEP. If no suitable candidate can be found, then the PEP will be marked as Deferred until one is available.
Previously appointed PEP-Delegates may choose to step down, or be asked to step down by the Council, in which case a new PEP-Delegate will be appointed in the same manner as for a new PEP (including deferral of the PEP if no suitable replacement can be found). In the event that a PEP-Delegate is asked to step down, this will overrule any prior acceptance or rejection of the PEP, and it will revert to Draft status.
When such standing delegations are put in place, the Steering Council will maintain sufficient public records to allow subsequent Councils, the core developers, and the wider Python community to understand the delegations that currently exist, why they were put in place, and the circumstances under which they may no longer be needed.
For a PEP to be accepted it must meet certain minimum criteria. It must be a clear and complete description of the proposed enhancement. The enhancement must represent a net improvement. The proposed implementation, if applicable, must be solid and must not complicate the interpreter unduly. Finally, a proposed enhancement must be “pythonic” in order to be accepted by the Steering Council. (However, “pythonic” is an imprecise term; it may be defined as whatever is acceptable to the Steering Council. This logic is intentionally circular.) See PEP 2 for standard library module acceptance criteria.
Except where otherwise approved by the Steering Council, pronouncements of PEP resolution will be posted to the PEPs category on the Python Discourse.
Once a PEP has been accepted, the reference implementation must be completed. When the reference implementation is complete and incorporated into the main source code repository, the status will be changed to “Final”.
To allow gathering of additional design and interface feedback before committing to long term stability for a language feature or standard library API, a PEP may also be marked as “Provisional”. This is short for “Provisionally Accepted”, and indicates that the proposal has been accepted for inclusion in the reference implementation, but additional user feedback is needed before the full design can be considered “Final”. Unlike regular accepted PEPs, provisionally accepted PEPs may still be Rejected or Withdrawn even after the related changes have been included in a Python release.
Wherever possible, it is considered preferable to reduce the scope of a proposal to avoid the need to rely on the “Provisional” status (e.g. by deferring some features to later PEPs), as this status can lead to version compatibility challenges in the wider Python ecosystem. PEP 411 provides additional details on potential use cases for the Provisional status.
A PEP can also be assigned the status “Deferred”. The PEP author or an editor can assign the PEP this status when no progress is being made on the PEP. Once a PEP is deferred, a PEP editor can reassign it to draft status.
A PEP can also be “Rejected”. Perhaps after all is said and done it was not a good idea. It is still important to have a record of this fact. The “Withdrawn” status is similar — it means that the PEP author themselves has decided that the PEP is actually a bad idea, or has accepted that a competing proposal is a better alternative.
When a PEP is Accepted, Rejected or Withdrawn, the PEP should be updated accordingly. In addition to updating the Status field, at the very least the Resolution header should be added with a direct link to the relevant post making a decision on the PEP.
PEPs can also be superseded by a different PEP, rendering the original obsolete. This is intended for Informational PEPs, where version 2 of an API can replace version 1.
The possible paths of the status of PEPs are as follows:
While not shown in the diagram, “Accepted” PEPs may technically move to “Rejected” or “Withdrawn” even after acceptance. This will only occur if the implementation process reveals fundamental flaws in the design that were not noticed prior to acceptance of the PEP. Unlike Provisional PEPs, these transitions are only permitted if the accepted proposal has not been included in a Python release — released changes must instead go through the regular deprecation process (which may require a new PEP providing the rationale for the deprecation).
Some Informational and Process PEPs may also have a status of “Active” if they are never meant to be completed. E.g. PEP 1 (this PEP).
PEP Maintenance
In general, PEPs are no longer substantially modified after they have reached the Accepted, Final, Rejected or Superseded state. Once resolution is reached, a PEP is considered a historical document rather than a living specification. Formal documentation of the expected behavior should be maintained elsewhere, such as the Language Reference for core features, the Library Reference for standard library modules or the PyPA Specifications for packaging.
If changes based on implementation experience and user feedback are made to Standards track PEPs while in the Provisional or (with SC approval) Accepted state, they should be noted in the PEP, such that the PEP accurately describes the implementation at the point where it is marked Final.
Active (Informational and Process) PEPs may be updated over time to reflect changes to development practices and other details. The precise process followed in these cases will depend on the nature and purpose of the PEP in question.
Occasionally, a Deferred or even a Withdrawn PEP may be resurrected with major updates, but it is often better to just propose a new one.
What belongs in a successful PEP?
Each PEP should have the following parts/sections:
- Preamble – RFC 2822 style headers containing meta-data about the PEP, including the PEP number, a short descriptive title (limited to a maximum of 44 characters), the names, and optionally the contact info for each author, etc.
- Abstract – a short (~200 word) description of the technical issue being addressed.
- Motivation – The motivation is critical for PEPs that want to change the Python language, library, or ecosystem. It should clearly explain why the existing language specification is inadequate to address the problem that the PEP solves. This can include collecting documented support for the PEP from important projects in the Python ecosystem. PEP submissions without sufficient motivation may be rejected.
- Rationale – The rationale fleshes out the specification by describing why particular design decisions were made. It should describe alternate designs that were considered and related work, e.g. how the feature is supported in other languages. The rationale should provide evidence of consensus within the community and discuss important objections or concerns raised during discussion.
- Specification – The technical specification should describe the syntax and semantics of any new language feature. The specification should be detailed enough to allow competing, interoperable implementations for at least the current major Python platforms (CPython, Jython, IronPython, PyPy).
- Backwards Compatibility – All PEPs that introduce backwards incompatibilities must include a section describing these incompatibilities and their severity. The PEP must explain how the author proposes to deal with these incompatibilities. PEP submissions without a sufficient backwards compatibility treatise may be rejected outright.
- Security Implications – If there are security concerns in relation to the PEP, those concerns should be explicitly written out to make sure reviewers of the PEP are aware of them.
- How to Teach This – For a PEP that adds new functionality or changes language behavior, it is helpful to include a section on how to teach users, new and experienced, how to apply the PEP to their work. This section may include key points and recommended documentation changes that would help users adopt a new feature or migrate their code to use a language change.
- Reference Implementation – The reference implementation must be completed before any PEP is given status “Final”, but it need not be completed before the PEP is accepted. While there is merit to the approach of reaching consensus on the specification and rationale before writing code, the principle of “rough consensus and running code” is still useful when it comes to resolving many discussions of API details. The final implementation must include test code and documentation appropriate for either the Python language reference or the standard library reference.
- Rejected Ideas – Throughout the discussion of a PEP, various ideas will be proposed which are not accepted. Those rejected ideas should be recorded along with the reasoning as to why they were rejected. This both helps record the thought process behind the final version of the PEP as well as preventing people from bringing up the same rejected idea again in subsequent discussions. In a way this section can be thought of as a breakout section of the Rationale section that is focused specifically on why certain ideas were not ultimately pursued.
- Open Issues – While a PEP is in draft, ideas can come up which warrant further discussion. Those ideas should be recorded so people know that they are being thought about but do not have a concrete resolution. This helps make sure all issues required for the PEP to be ready for consideration are complete and reduces people duplicating prior discussion.
- Footnotes – A collection of footnotes cited in the PEP, and a place to list non-inline hyperlink targets.
- Copyright/license – Each new PEP must be placed under a dual license of public domain and CC0-1.0-Universal (see this PEP for an example).
PEP Formats and Templates
PEPs are UTF-8 encoded text files using the reStructuredText format. reStructuredText allows for rich markup that is still quite easy to read, but also results in good-looking and functional HTML. PEP 12 contains instructions and a PEP template.
The PEP text files are automatically converted to HTML (via a Sphinx-based build system) for easier online reading.
PEP Header Preamble
Each PEP must begin with an RFC 2822 style header preamble. The headers must appear in the following order. Headers marked with “*” are optional and are described below. All other headers are required.
PEP: Title: Author: * Sponsor: * PEP-Delegate: Discussions-To: Status: Type: * Topic: * Requires: Created: * Python-Version: Post-History: * Replaces: * Superseded-By: * Resolution:
The Author header lists the names, and optionally the email addresses of all the authors/owners of the PEP. The format of the Author header values must be:
Random J. User
if the email address is included, and just:
Random J. User
if the address is not given.
If there are multiple authors, each should be on a separate line following RFC 2822 continuation line conventions. Note that personal email addresses in PEPs will be obscured as a defense against spam harvesters.
The Sponsor field records which developer (core, or otherwise approved by the Steering Council) is sponsoring the PEP. If one of the authors of the PEP is a core developer then no sponsor is necessary and thus this field should be left out.
The PEP-Delegate field is used to record the individual appointed by the Steering Council to make the final decision on whether or not to approve or reject a PEP. (The delegate’s email address is currently omitted due to a limitation in the email address masking for reStructuredText PEPs.)
Note: The Resolution header is required for Standards Track PEPs only. It contains a URL that should point to an email message or other web resource where the pronouncement about (i.e. approval or rejection of) the PEP is made.
The Discussions-To header provides the URL to the current canonical discussion thread for the PEP. For email lists, this should be a direct link to the thread in the list’s archives, rather than just a mailto: or hyperlink to the list itself.
The Type header specifies the type of PEP: Standards Track, Informational, or Process.
The optional Topic header lists the special topic, if any, the PEP belongs under. See the Topic Index for the existing topics.
The Created header records the date that the PEP was assigned a number, while Post-History is used to record the dates of and corresponding URLs to the Discussions-To threads for the PEP, with the former as the linked text, and the latter as the link target. Both sets of dates should be in dd-mmm-yyyy format, e.g. 14-Aug-2001 .
Standards Track PEPs will typically have a Python-Version header which indicates the version of Python that the feature will be released with. Standards Track PEPs without a Python-Version header indicate interoperability standards that will initially be supported through external libraries and tools, and then potentially supplemented by a later PEP to add support to the standard library. Informational and Process PEPs do not need a Python-Version header.
PEPs may have a Requires header, indicating the PEP numbers that this PEP depends on.
PEPs may also have a Superseded-By header indicating that a PEP has been rendered obsolete by a later document; the value is the number of the PEP that replaces the current document. The newer PEP must have a Replaces header containing the number of the PEP that it rendered obsolete.
Auxiliary Files
PEPs may include auxiliary files such as diagrams. Such files should be named pep-XXXX-Y.ext , where “XXXX” is the PEP number, “Y” is a serial number (starting at 1), and “ext” is replaced by the actual file extension (e.g. “png”).
Alternatively, all support files may be placed in a subdirectory called pep-XXXX , where “XXXX” is the PEP number. When using a subdirectory, there are no constraints on the names used in files.
Changing Existing PEPs
Draft PEPs are freely open for discussion and proposed modification, at the discretion of the authors, until submitted to the Steering Council or PEP-Delegate for review and resolution. Substantive content changes should generally be first proposed on the PEP’s discussion thread listed in its Discussions-To header, while copyedits and corrections can be submitted as a GitHub issue or GitHub pull request. PEP authors with write access to the PEP repository can update the PEPs themselves by using git push or a GitHub PR to submit their changes. For guidance on modifying other PEPs, consult the PEP Maintenance section.
See the Contributing Guide for additional details, and when in doubt, please check first with the PEP author and/or a PEP editor.
Transferring PEP Ownership
It occasionally becomes necessary to transfer ownership of PEPs to a new champion. In general, it is preferable to retain the original author as a co-author of the transferred PEP, but that’s really up to the original author. A good reason to transfer ownership is because the original author no longer has the time or interest in updating it or following through with the PEP process, or has fallen off the face of the ‘net (i.e. is unreachable or not responding to email). A bad reason to transfer ownership is because the author doesn’t agree with the direction of the PEP. One aim of the PEP process is to try to build consensus around a PEP, but if that’s not possible, an author can always submit a competing PEP.
If you are interested in assuming ownership of a PEP, you can also do this via pull request. Fork the PEP repository, make your ownership modification, and submit a pull request. You should mention both the original author and @python/pep-editors in a comment on the pull request. (If the original author’s GitHub username is unknown, use email.) If the original author doesn’t respond in a timely manner, the PEP editors will make a unilateral decision (it’s not like such decisions can’t be reversed :).
PEP Editor Responsibilities & Workflow
A PEP editor must be added to the @python/pep-editors group on GitHub and must watch the PEP repository.
Note that developers with write access to the PEP repository may handle the tasks that would normally be taken care of by the PEP editors. Alternately, even developers may request assistance from PEP editors by mentioning @python/pep-editors on GitHub.
For each new PEP that comes in an editor does the following:
- Make sure that the PEP is either co-authored by a core developer, has a core developer as a sponsor, or has a sponsor specifically approved for this PEP by the Steering Council.
- Read the PEP to check if it is ready: sound and complete. The ideas must make technical sense, even if they don’t seem likely to be accepted.
- The title should accurately describe the content.
- The file name extension is correct (i.e. .rst ).
- Ensure that everyone listed as a sponsor or co-author of the PEP who has write access to the PEP repository is added to .github/CODEOWNERS.
- Skim the PEP for obvious defects in language (spelling, grammar, sentence structure, etc.), and code style (examples should conform to PEP 7 & PEP 8). Editors may correct problems themselves, but are not required to do so (reStructuredText syntax is checked by the repo’s CI).
- If a project is portrayed as benefiting from or supporting the PEP, make sure there is some direct indication from the project included to make the support clear. This is to avoid a PEP accidentally portraying a project as supporting a PEP when in fact the support is based on conjecture.
If the PEP isn’t ready, an editor will send it back to the author for revision, with specific instructions. If reST formatting is a problem, ask the author(s) to use PEP 12 as a template and resubmit.
Once the PEP is ready for the repository, a PEP editor will:
- Check that the author has selected a valid PEP number or assign them a number if they have not (almost always just the next available number, but sometimes it’s a special/joke number, like 666 or 3141). Remember that numbers below 100 are meta-PEPs.
- Check that the author has correctly labeled the PEP’s type (“Standards Track”, “Informational”, or “Process”), and marked its status as “Draft”.
- Ensure all CI build and lint checks pass without errors, and there are no obvious issues in the rendered preview output.
- Merge the new (or updated) PEP.
- Inform the author of the next steps (open a discussion thread and update the PEP with it, post an announcement, etc).
Updates to existing PEPs should be submitted as a GitHub pull request.
Many PEPs are written and maintained by developers with write access to the Python codebase. The PEP editors monitor the PEP repository for changes, and correct any structure, grammar, spelling, or markup mistakes they see.
PEP editors don’t pass judgment on PEPs. They merely do the administrative & editorial part (which is generally a low volume task).
- Index of Python Enhancement Proposals
- Following Python’s Development
- Python Developer’s Guide
Copyright
This document is placed in the public domain or under the CC0-1.0-Universal license, whichever is more permissive.
PEP 8
Python, подобно живому организму, развивается и приобретает новые возможности благодаря многочисленному международному сообществу согласно определенным правилам и стандартам PEP . PEP — Python Enhancement Proposal, предложения по развитию Python. Эти стандарты позволяют создавать унифицированную проектную документацию для новых утвержденных возможностей языка Python. Самый известный PEP имеет восьмой порядковый номер. PEP8 содержит перечень принципов написания красивого и лаконичного программного кода на языке Python.
Под названием каждого подраздела главы будет находиться по одному из 19 принципов философии Python (Zen of Python) . Попытайтесь «прочувствовать» то, что имел в виду автор. Также, если хочется, вместо русской адаптации этих постулатов, увидеть оригинальный текст Тима Петерса , можно запустив вот такую программу.
import thisДля чего придуман PEP8? ¶
(Читаемость имеет значение)
PEP8 существует, чтобы улучшить «читабельность» кода. Но почему этот параметр имеет настолько большую важность? Почему написание хорошо читаемого кода — один из фундаментальных принципов языка Python?
Как сказал создатель Python, Гвидо Ван Россум: «Код читается гораздо чаще, чем пишется». Вы можете провести несколько минут, или весь день, в процессе написания куска кода для, к примеру, аутентификации пользователя. Написав его, однажды, вы не будете писать его еще раз. Но вы точно вернетесь, чтобы прочитать его еще и еще раз. Эта часть кода может быть частью проекта, над которым вы работаете. Каждый раз, возвращаясь к этому файлу, придется вспомнить, что этот код делает и почему вы написали это именно так.
Если вы начинающий программист Python, вам может быть тяжело запомнить, что делает определенная часть кода по прошествии нескольких дней после ее написания. Однако, если вы будете следовать рекомендациям PEP8, можете быть уверены, ваш код будет в полном порядке. Вы будете знать, что добавили достаточно пробелов, в соответствии с разделением на логические блоки кода.
Соблюдение PEP8 особенно важно, если вы в поисках вакансии python-разработчика. Чистый и читаемый код показывает высокий профессионализм. Он говорит работодателю о вашем понимании правильного структурирования программного кода.
Если же вы более опытный Python-программист, тогда с помощи PEP8 можно с легкостью объединиться с другими программистами для работы над одной задачей. Хорошо читаемый код имеет в данном случае особую критичность. Люди, ранее не видевшие вас, но знакомые с вашим кодом, будут читать, понимая идею, которую вы хотели донести.
Негласная договоренность об именах ¶
(Явное лучше, чем неявное)
При написании Python кода, необходимо придумывать имена многим вещам: переменным, функциям, классам, пакетам и так далее. Выбор разумных имен сэкономит вам время и силы в последствии. По названию нужно суметь понять, что представляет собой определенная переменная, функция или класс. Вы также избежите использования некорректных имен, которые могут привести к критическим ошибкам, плохо поддающимся отладке.
Не использовать одиночные буквы l, O, или I в качестве каких-либо имен из-за риска спутать их с 1 и 0, в зависимости от шрифта.
O = 2 # Это может выглядеть так, будто вы хотите приравнять 2 к нулю.Стили именования ¶
В таблице ниже описаны некоторые из распространенных стилей именования в коде Python и указаны случаи, когда их следует использовать:
Тип Соглашение об именовании Примеры Функции Используйте слово или слова в нижнем регистре. Для удобства чтения разделяйте слова подчеркиванием. function, my_function Переменные Используйте одну строчную букву, слово или слова. Для удобства чтения разделяйте слова подчеркиванием. x, var, my_variable Классы Каждое слово начинайте с заглавной буквы. Не разделяйте слова подчеркиванием. Этот стиль называется «дело верблюда». Model, MyClass Методы Используйте слово или слова в нижнем регистре. Для удобства чтения разделяйте слова подчеркиванием. class_method, method Константы Используйте одну заглавную букву, слово или слова. Для удобства чтения разделяйте слова подчеркиванием. CONSTANT, MY_CONSTANT, MY_LONG_CONSTANT Модули Используйте короткие слова или слова в нижнем регистре. Для удобства чтения разделяйте слова подчеркиванием. module.py, my_module.py Пакеты Используйте короткие слова или слова в нижнем регистре. Не разделяйте слова подчеркиванием. package, mypackage Помимо выбора правильных стилей именования в вашем коде, вы также должны тщательно выбирать сами имена. Ниже приведены несколько советов, как сделать это максимально эффективно.
Правильный выбор имени ¶
Выбор имен для переменных, функций, классов и т. д. может оказаться неожиданно сложной задачей. При написании кода вы должны хорошо продумать свой выбор имен, так как это сделает ваш код более читаемым. Лучший способ назвать ваши объекты в Python — использовать описательные имена, чтобы было понятно, что представляет собой объект.
При именовании переменных у вас может возникнуть соблазн выбрать простые, состоящие из одной буквы имена в нижнем регистре, например x . Но если вы не используете x в качестве аргумента математической функции, непонятно, что представляет собой этот самый x . Представьте, что вы храните имя человека в виде строки и хотите использовать срез строки, чтобы по-другому отформатировать его имя.
Вы можете получить что-то вроде этого:
# Не рекомендуетсяx = 'Иван Петров'y, z = x.split()Это будет работать, но вам нужно будет отслеживать, что представляют собой x , y и z . Это также может сбивать с толку соавторов. Более правильный выбор имен будет примерно таким:
# Рекомендуетсяname = 'Иван Петров'first_name, last_name = name.split()Точно так же, чтобы уменьшить количество набираемых вами букв, может возникнуть соблазн использовать сокращения при выборе имен. В приведенном ниже примере была определена функция db , которая принимает единственный аргумент x и удваивает его:
# Не рекомендуетсяdef db(x):return x * 2На первый взгляд, это может показаться очевидным выбором — это ведь отличное сокращением для double ! Но представьте, что вернетесь к этому коду через несколько дней. Скорее всего, вы забудете, какой смысл вкладывали в эту функцию и вполне можете подумать, что это сокращение от database .
Следующий пример еще более понятен:
# Рекомендуетсяdef multiply_by_two(x):return x * 2Та же самая философия относится и ко всем прочим типам данных и объектов в Python. Всегда пробуйте использовать наиболее емкие и лаконичные названия.
Расположение кода ¶
(Красивое лучше, чем уродливое)
То, как Вы расположите ваш код, имеет огромную роль в повышении его читаемость. В этом разделе вы узнаете, как добавить вертикальные пробелы для улучшения восприятия вашего кода. Вы также узнаете, как правильно пользоваться ограничением в 79 символов на строку, рекомендованным в PEP8.
Монолитный код может быть труден для восприятия. Точно так же, слишком много пустых строк в коде делает его очень разреженным, что заставит читателя пролистывать его чаще, чем необходимо. Ниже приведены три основных правила использования вертикальных пробелов.
Окружите функции и классы верхнего уровня двумя пустыми строками. Функции и классы верхнего уровня должны быть самодостаточны и обрабатывать отдельные функции. Имеет смысл разместить вокруг них дополнительное вертикальное пространство, чтобы было ясно, что они разделены:
class MyFirstClass:passclass MySecondClass:passdef top_level_function():return NoneОбособьте определения методов внутри классов одной пустой строкой. Внутри класса все функции связаны друг с другом. Рекомендуется оставлять между ними только одну строку:
class MyClass:def first_method(self):return Nonedef second_method(self):return NoneИспользуйте пустые строки внутри функций, чтобы четко показать шаги. Иногда сложная функция должна выполнить несколько шагов перед оператором return . Чтобы помочь читателю понять логику внутри функции, может быть полезно оставлять пустую строку между каждым шагом.
В приведенном ниже примере есть функция для вычисления дисперсии списка. Это двухэтапная задача, поэтому логично будет отделить каждый шаг, оставив между ними пустую строку. Перед оператором возврата также есть пустая строка. Это помогает читателю ясно увидеть, что возвращается:
def calculate_variance(number_list):sum_list = 0for number in number_list:sum_list = sum_list + numbermean = sum_list / len(number_list)sum_squares = 0for number in number_list:sum_squares = sum_squares + number**2mean_squares = sum_squares / len(number_list)return mean_squares - mean**2Если вы правильно используете вертикальные пробелы, это может значительно улучшить читаемость вашего кода и помочь читателю визуально понять, что этот код делает.
Максимальная длина строки и разрыв строки ¶
PEP8 предлагает ограничить длину строки 79 символами. Это рекомендуется делать, чтобы вы имели возможность открывать несколько файлов рядом друг с другом, а также избегать переноса строк.
Конечно, не всегда возможно обеспечить длины всех операторов до 79 символов. PEP8 также описывает способы, позволяющие операторам занимать несколько строк. Python предполагает наличие продолжения строки, если код заключен в круглые, квадратные или фигурные скобки:
def function(arg_one, arg_two,arg_three, arg_four):return arg_oneЕсли продолжение строки использовать не представляется возможным, можно также использовать обратную косую черту для разрыва строки:
from mypkg import example1, \example2, example3Важно: если разрыв строки должен произойти вокруг бинарных операторов, таких как сложение или, например, умножение, он должен находиться перед оператором.
Отступы ¶
(Должен быть один очевидный способ сделать это)
Отступы или же пробелы в начале строки — крайне важная часть в синтаксисе Python. Как группируются операторы друг с другом операторы, в Python определяют именно уровни строк.
x = 2if x > 6:print('x больше, чем 6')Отступ перед оператором вывода дает сигнал Python об условном выполнении только в случае, когда оператор if возвращает True . Ровно такой же отступ покажет Python, какой именно код выполнять при вызове функции или какой код имеет отношение к данному классу. Ключевых правил расстановки отступов всего два и они ниже:
- Используйте четыре последовательных пробела для отступа;
- Отдавайте предпочтение пробелам, а не табуляции.
Пробелы против Табуляции ¶
Вы можете настроить ваш редактор кода на вставку четырех пробелов, когда вы нажимаете клавишу Tab. Также необходимо иметь в виду, что в Python 3 запрещено смешение пробелов и табуляции. Изначально выберите, как именно вы будете выставлять отступы и придерживайтесь этого выбора. Иначе, вместо выполнения кода, вы получите ошибку.
Комментарии ¶
(Если реализацию трудно объяснить, это была плохая идея)
Используйте комментарии для документирования кода в том виде, в каком он написан. Это важно для ваших коллег и вашего понимания своего кода в будущем. Вот три важных ключевых момента, которые необходимо учитывать, при добавлении комментариев к коду:
- Используйте длину комментариев при документации не более 72 символов;
- Не используйте сокращения, начинайте предложения с заглавной буквы;
- Не забывайте актуализировать комментарии, при изменении кода.
Пример простейшего комментария:
name = 'John Smith' # Student NameПробелы в выражениях и утверждениях ¶
(Разреженное лучше, чем плотное)
Полезность пробелов в выражениях и операторах трудно переоценить. Если пробелов недостаточно, код может быть трудночитаемым, так как все сгруппированы вместе. Если пробелов слишком много, может быть сложно визуально объединить строки кода в, логически связанные, блоки.
Окружите следующие бинарные операторы одним пробелом с каждой стороны:
- Операторы присвоения (=, +=, -= и т. п.)
- Сравнения (==, ! =, >,
- Логические (and, or, not)
Когда = используется для присвоения значения для аргумента функции, не окружайте его пробелами.
Рекомендации программисту ¶
(Простое лучше сложного)
Необходимо заметить, что в Python можно придумать несколько способов для выполнения одного и того же действия. Далее будет рассказано, как избавляться от двусмысленности при сохранении последовательности.
# Не рекомендуетсяmy_bool = 4 > 3if my_bool == True:return '4 больше 3'Использование оператора эквивалентности здесь не имеет необходимости, my_bool может иметь только два значения, True или False. Поэтому достаточно написать так:
# Рекомендуетсяif my_bool:return '4 is bigger than 3'Этот способ выполнения оператора if с логическим оператором проще и требует меньше кода, поэтому PEP8 рекомендует именно его.
Когда лучше проигнорировать PEP8 ¶
Однозначно ответить на этот вопрос довольно сложно. Если вы безукоризненно исполняете все предписания PEP8, можно с уверенностью гарантировать «чистоту», высокий уровень читаемости кода и профессионализм программиста. Что принесет пользу всем взаимодействующим с вашим кодом, от коллег до конечного заказчика продукта. Но все же некоторые рекомендации PEP8 неприменимы в следующих случаях:
- Если соблюдение PEP8 нарушит совместимость с существующим программным обеспечением;
- Если код, сопутствующий тому, над чем вы работаете, несовместим с PEP8;
- Если код нужно оставить совместимым с неактуальными версиями Python.
Заключение ¶
Теперь вам должно стать понятны способы создания высококачественного, читаемого кода Python, с помощью рекомендаций PEP8. Хотя они могут показаться тюрьмой для мозга творца, их соблюдение действительно может «прокачать» ваш код, в частности, когда речь заходит о разделении работы над ним с соавторами.
Если же у вас имеется желание углубиться в изучение тонкостей PEP8, можно ознакомиться с полной англоязычной документацией или посетить информационный ресурс pep8.org , содержащий ту же информацию, в более структурированном виде. В этих документах вы найдете, не попавшие в эту «выжимку», рекомендации.
Хотите выучить Python на практике?
