1. Какие имена являются правильными B PYTHON: ○_ab
○41N
○a+b
○Game 2
2.Имена переменных не могут включать:
○Цифры
○Русские буквы,Скобки знаки + =!? b. др
○Пробелы
○Латинские буквы
СОРЧНО ПОМОГИТЕ ПЖ

Имена a+b и Game 2 не являются правильными, так как содержат недопустимые символы.
Имена переменных не могут включать русские буквы, скобки, знаки + = !? и другие символы, которые не относятся к латинскому алфавиту и цифрам. Поэтому правильный вариант ответа — b. др.
Самоучитель
Python, подобно живому организму, развивается и приобретает новые возможности благодаря многочисленному международному сообществу согласно определенным правилам и стандартам PEP. PEP – Python Enhancement Proposal, предложения по развитию Python. Эти стандарты позволяют создавать унифицированную проектную документацию для новых утвержденных возможностей языка Python. Самый известный PEP имеет восьмой порядковый номер. PEP8 содержит перечень принципов написания красивого и лаконичного программного кода на языке Python.
Под названием каждого подраздела главы будет находиться по одному из 19 принципов философии Python (Zen of Python). Попытайтесь «прочувствовать» то, что имел в виду автор. Также, если хочется, вместо русской адаптации этих постулатов, увидеть оригинальный текст Тима Петерса, можно запустив вот такую программу.
Для чего придуман PEP8?
(Читаемость имеет значение)
PEP8 существует, чтобы улучшить “читабельность„ кода. Но почему этот параметр имеет настолько большую важность? Почему написание хорошо читаемого кода – один из фундаментальных принципов языка Python?
Как сказал создатель Python, Гвидо Ван Россум: «Код читается гораздо чаще, чем пишется». Вы можете провести несколько минут, или весь день, в процессе написания куска кода для, к примеру, аутентификации пользователя. Написав его, однажды, вы не будете писать его еще раз. Но вы точно вернетесь, чтобы прочитать его еще и еще раз. Эта часть кода может быть частью проекта, над которым вы работаете. Каждый раз, возвращаясь к этому файлу, придется вспомнить, что этот код делает и почему вы написали это именно так.
Если вы начинающий программист Python, вам может быть тяжело запомнить, что делает определенная часть кода по прошествии нескольких дней после ее написания. Однако, если вы будете следовать рекомендациям PEP8, можете быть уверены, ваш код будет в полном порядке. Вы будете знать, что добавили достаточно пробелов, в соответствии с разделением на логические блоки кода.
Соблюдение PEP8 особенно важно, если вы в поисках вакансии python-разработчика. Чистый и читаемый код показывает высокий профессионализм. Он говорит работодателю о вашем понимании правильного структурирования программного кода.
Если же вы более опытный Python-программист, тогда с помощи PEP8 можно с легкостью объединиться с другими программистами для работы над одной задачей. Хорошо читаемый код имеет в данном случае особую критичность. Люди, ранее не видевшие вас, но знакомые с вашим кодом, будут читать, понимая идею, которую вы хотели донести.
Негласная договоренность об именах
(Явное лучше, чем неявное)
При написании Python кода, необходимо придумывать имена многим вещам: переменным, функциям, классам, пакетам и так далее. Выбор разумных имен сэкономит вам время и силы в последствии. По названию нужно суметь понять, что представляет собой определенная переменная, функция или класс. Вы также избежите использования некорректных имен, которые могут привести к критическим ошибкам, плохо поддающимся отладке.
Не использовать одиночные буквы l, O, или I в качестве каких‑либо имен из‑за риска спутать их с 1 и 0, в зависимости от шрифта.
Стили именования
В таблице ниже описаны некоторые из распространенных стилей именования в коде 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. Это также может сбивать с толку соавторов. Более правильный выбор имен будет примерно таким:
Точно так же, чтобы уменьшить количество набираемых вами букв, может возникнуть соблазн использовать сокращения при выборе имен. В приведенном ниже примере была определена функция db, которая принимает единственный аргумент x и удваивает его:
На первый взгляд, это может показаться очевидным выбором — это ведь отличное сокращением для double! Но представьте, что вернетесь к этому коду через несколько дней. Скорее всего, вы забудете, какой смысл вкладывали в эту функцию и вполне можете подумать, что это сокращение от database.
Следующий пример еще более понятен:
Та же самая философия относится и ко всем прочим типам данных и объектов в Python. Всегда пробуйте использовать наиболее емкие и лаконичные названия.
Расположение кода
(Красивое лучше, чем уродливое)
То, как Вы расположите ваш код, имеет огромную роль в повышении его читаемость. В этом разделе вы узнаете, как добавить вертикальные пробелы для улучшения восприятия вашего кода. Вы также узнаете, как правильно пользоваться ограничением в 79 символов на строку, рекомендованным в PEP8.
Монолитный код может быть труден для восприятия. Точно так же, слишком много пустых строк в коде делает его очень разреженным, что заставит читателя пролистывать его чаще, чем необходимо. Ниже приведены три основных правила использования вертикальных пробелов.
Окружите функции и классы верхнего уровня двумя пустыми строками. Функции и классы верхнего уровня должны быть самодостаточны и обрабатывать отдельные функции. Имеет смысл разместить вокруг них дополнительное вертикальное пространство, чтобы было ясно, что они разделены:
Обособьте определения методов внутри классов одной пустой строкой. Внутри класса все функции связаны друг с другом. Рекомендуется оставлять между ними только одну строку:
Используйте пустые строки внутри функций, чтобы четко показать шаги. Иногда сложная функция должна выполнить несколько шагов перед оператором return. Чтобы помочь читателю понять логику внутри функции, может быть полезно оставлять пустую строку между каждым шагом.
В приведенном ниже примере есть функция для вычисления дисперсии списка. Это двухэтапная задача, поэтому логично будет отделить каждый шаг, оставив между ними пустую строку. Перед оператором возврата также есть пустая строка. Это помогает читателю ясно увидеть, что возвращается:
Если вы правильно используете вертикальные пробелы, это может значительно улучшить читаемость вашего кода и помочь читателю визуально понять, что этот код делает.
Максимальная длина строки и разрыв строки
PEP8 предлагает ограничить длину строки 79 символами. Это рекомендуется делать, чтобы вы имели возможность открывать несколько файлов рядом друг с другом, а также избегать переноса строк.
Конечно, не всегда возможно обеспечить длины всех операторов до 79 символов. PEP8 также описывает способы, позволяющие операторам занимать несколько строк. Python предполагает наличие продолжения строки, если код заключен в круглые, квадратные или фигурные скобки:
Если продолжение строки использовать не представляется возможным, можно также использовать обратную косую черту для разрыва строки:
Важно: если разрыв строки должен произойти вокруг бинарных операторов, таких как сложение или, например, умножение, он должен находиться перед оператором.
Отступы
(Должен быть один очевидный способ сделать это)
Отступы или же пробелы в начале строки — крайне важная часть в синтаксисе Python. Как группируются операторы друг с другом операторы, в Python определяют именно уровни строк.
Отступ перед оператором вывода дает сигнал Python об условном выполнении только в случае, когда оператор if возвращает True. Ровно такой же отступ покажет Python, какой именно код выполнять при вызове функции или какой код имеет отношение к данному классу. Ключевых правил расстановки отступов всего два и они ниже:
Используйте четыре последовательных пробела для отступа;
Отдавайте предпочтение пробелам, а не табуляции.
Пробелы против Табуляции
Вы можете настроить ваш редактор кода на вставку четырех пробелов, когда вы нажимаете клавишу Tab. Также необходимо иметь в виду, что в Python 3 запрещено смешение пробелов и табуляции. Изначально выберите, как именно вы будете выставлять отступы и придерживайтесь этого выбора. Иначе, вместо выполнения кода, вы получите ошибку.
Комментарии
(Если реализацию трудно объяснить, это была плохая идея)
Используйте комментарии для документирования кода в том виде, в каком он написан. Это важно для ваших коллег и вашего понимания своего кода в будущем. Вот три важных ключевых момента, которые необходимо учитывать, при добавлении комментариев к коду:
Используйте длину комментариев при документации не более 72 символов;
Не используйте сокращения, начинайте предложения с заглавной буквы;
Не забывайте актуализировать комментарии, при изменении кода.
Пример простейшего комментария:
Пробелы в выражениях и утверждениях
(Разреженное лучше, чем плотное)
Полезность пробелов в выражениях и операторах трудно переоценить. Если пробелов недостаточно, код может быть трудночитаемым, так как все сгруппированы вместе. Если пробелов слишком много, может быть сложно визуально объединить строки кода в, логически связанные, блоки.
Окружите следующие бинарные операторы одним пробелом с каждой стороны:
Операторы присвоения ( =, +=, -= и т. п.)
Сравнения ( ==, !=, >, <. >=, <= ) и (is, is not, in, not in)
Логические (and, or, not)
Когда = используется для присвоения значения для аргумента функции, не окружайте его пробелами.
Рекомендации программисту
(Простое лучше сложного)
Необходимо заметить, что в Python можно придумать несколько способов для выполнения одного и того же действия. Далее будет рассказано, как избавляться от двусмысленности при сохранении последовательности.
Использование оператора эквивалентности здесь не имеет необходимости, my_bool может иметь только два значения, True или False. Поэтому достаточно написать так:
Этот способ выполнения оператора if с логическим оператором проще и требует меньше кода, поэтому PEP8 рекомендует именно его.
Когда лучше проигнорировать PEP8
Однозначно ответить на этот вопрос довольно сложно. Если вы безукоризненно исполняете все предписания PEP8, можно с уверенностью гарантировать «чистоту», высокий уровень читаемости кода и профессионализм программиста. Что принесет пользу всем взаимодействующим с вашим кодом, от коллег до конечного заказчика продукта. Но все же некоторые рекомендации PEP8 неприменимы в следующих случаях:
Если соблюдение PEP8 нарушит совместимость с существующим программным обеспечением;
Если код, сопутствующий тому, над чем вы работаете, несовместим с PEP8;
Если код нужно оставить совместимым с неактуальными версиями Python.
Заключение
Теперь вам должно стать понятны способы создания высококачественного, читаемого кода Python, с помощью рекомендаций PEP8. Хотя они могут показаться тюрьмой для мозга творца, их соблюдение действительно может «прокачать» ваш код, в частности, когда речь заходит о разделении работы над ним с соавторами.
Если же у вас имеется желание углубиться в изучение тонкостей PEP8, можно ознакомиться с полной англоязычной документацией или посетить информационный ресурс pep8.org, содержащий ту же информацию, в более структурированном виде. В этих документах вы найдете, не попавшие в эту «выжимку», рекомендации.
Правильный выбор имен переменных в Python
Будучи единоличным хозяином своей программы, вы вправе выбирать имена переменным. В прошлой статье я решил назвать переменную name, но с тем же успехом можно было бы ее именовать human, nickname или даже omega12345666: работа программы нисколько не изменилась бы.
Для создания корректных имен переменных надо следовать всего нескольким правилам; о некорректном имени Python вам сообщит, выведя ошибку.
Итак, важнейших правил два:
- имя переменной может состоять только из цифр, букв и знаков подчеркивания;
- имя переменной не может начинаться с цифры.
Вдобавок к этим двум абсолютным законам есть несколько негласных правил, которым следуют все опытные программисты.
Вы тоже, приобретя некоторый опыт, почувствуете разницу между “просто корректными” и “хорошими” именами переменным(приведу пример прямо сейчас: имя omega12345666 – корректное, но очень, очень плохое). Перечислю основное, что надо и нужно запомнить.
Имя должно описывать суть. Следует называть переменные так, чтобы другой программист, взглянув на ваш код, смог толком разобраться, что есть что. Поnэтому, например, score лучше, чем s.
Исключение – кратковременно действующие переменные, которым программисты склонны присваивать короткие имена, например х. Но даже этот случай нельзя считать подлинным исключением, ведь, называя переменную х, программист дает понять, что она временная.
Будьте последовательны. Есть много разных позиций по вопросу о том, как лучше оформлять имена переменных, составленные из нескольких слов. Будет ли лучше, например, написать high_score или highScore?
Я привык пользоваться подчеркиванием.Отнюдь не важно, какой системы вы придерживаетесь, лишь бы вы следовали все время только ей, хотя по стандарту оформления программ правильно использовать для переменных и функций именно подчеркивания.
Уважайте обычай языка. Некоторые правила именования переменных – всего лишь дань традиции. Так, в большинстве языков программирования, в том числе и в Python, имя переменной принято начинать со строчной буквы.
Другая традиция состоит в том, чтобы избегать подчеркиваний в качестве начальных символов в именах переменных (у имен с начальным подчеркиванием в Python особый смысл).
Следите за длиной. Иногда эта рекомендация может вступать в противоречие с первой, требующей от имен переменных описательной силы. В самом деле, разве удобно пользоваться таким, например, именем: persona1_checking_account_bаlance’? Видимо, нет.Чересчур длинные имена переменных проблематичны, в частности, тем, что загромождают код.
А кроме того, чем длиннее имя, тем выше риск сделать в нем опечатку. Советую вам не создавать имена длиннее 15 символов.
Кстати, самодокументирующим называется код, из которого даже без комментариев легко понять, что происходит в программе. «Говорящие» имена переменных – немаловажный шаг на пути к созданию такого кода.
Вот что случится если объявить переменную ошибочно, то есть начать переменную с цифрами:
PEP 8 – Style Guide for Python Code
This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python.
This document and PEP 257 (Docstring Conventions) were adapted from Guido’s original Python Style Guide essay, with some additions from Barry’s style guide [2].
This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in the language itself.
Many projects have their own coding style guidelines. In the event of any conflicts, such project-specific guides take precedence for that project.
A Foolish Consistency is the Hobgoblin of Little Minds
One of Guido’s key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, “Readability counts”.
A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.
However, know when to be inconsistent – sometimes style guide recommendations just aren’t applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don’t hesitate to ask!
In particular: do not break backwards compatibility just to comply with this PEP!
Some other good reasons to ignore a particular guideline:
- When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
- To be consistent with surrounding code that also breaks it (maybe for historic reasons) – although this is also an opportunity to clean up someone else’s mess (in true XP style).
- Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.
- When the code needs to remain compatible with older versions of Python that don’t support the feature recommended by the style guide.
Code Lay-out
Indentation
Use 4 spaces per indentation level.
Continuation lines should align wrapped elements either vertically using Python’s implicit line joining inside parentheses, brackets and braces, or using a hanging indent [1]. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line:
The 4-space rule is optional for continuation lines.
When the conditional part of an if -statement is long enough to require that it be written across multiple lines, it’s worth noting that the combination of a two character keyword (i.e. if ), plus a single space, plus an opening parenthesis creates a natural 4-space indent for the subsequent lines of the multiline conditional. This can produce a visual conflict with the indented suite of code nested inside the if -statement, which would also naturally be indented to 4 spaces. This PEP takes no explicit position on how (or whether) to further visually distinguish such conditional lines from the nested suite inside the if -statement. Acceptable options in this situation include, but are not limited to:
(Also see the discussion of whether to break before or after binary operators below.)
The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character of the last line of list, as in:
or it may be lined up under the first character of the line that starts the multiline construct, as in:
Tabs or Spaces?
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
Python disallows mixing tabs and spaces for indentation.
Maximum Line Length
Limit all lines to a maximum of 79 characters.
For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.
Limiting the required editor window width makes it possible to have several files open side by side, and works well when using code review tools that present the two versions in adjacent columns.
The default wrapping in most tools disrupts the visual structure of the code, making it more difficult to understand. The limits are chosen to avoid wrapping in editors with the window width set to 80, even if the tool places a marker glyph in the final column when wrapping lines. Some web based tools may not offer dynamic line wrapping at all.
Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 99 characters, provided that comments and docstrings are still wrapped at 72 characters.
The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72).
The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
Backslashes may still be appropriate at times. For example, long, multiple with -statements could not use implicit continuation before Python 3.10, so backslashes were acceptable for that case:
(See the previous discussion on multiline if-statements for further thoughts on the indentation of such multiline with -statements.)
Another such case is with assert statements.
Make sure to indent the continued line appropriately.
Should a Line Break Before or After a Binary Operator?
For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line. Here, the eye has to do extra work to tell which items are added and which are subtracted:
To solve this readability problem, mathematicians and their publishers follow the opposite convention. Donald Knuth explains the traditional rule in his Computers and Typesetting series: “Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations” [3].
Following the tradition from mathematics usually results in more readable code:
In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth’s style is suggested.
Blank Lines
Surround top-level function and class definitions with two blank lines.
Method definitions inside a class are surrounded by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Python accepts the control-L (i.e. ^L) form feed character as whitespace; many tools treat these characters as page separators, so you may use them to separate pages of related sections of your file. Note, some editors and web-based code viewers may not recognize control-L as a form feed and will show another glyph in its place.
Source File Encoding
Code in the core Python distribution should always use UTF-8, and should not have an encoding declaration.
In the standard library, non-UTF-8 encodings should be used only for test purposes. Use non-ASCII characters sparingly, preferably only to denote places and human names. If using non-ASCII characters as data, avoid noisy Unicode characters like z̯̯͡a̧͎̺l̡͓̫g̹̲o̡̼̘ and byte order marks.
All identifiers in the Python standard library MUST use ASCII-only identifiers, and SHOULD use English words wherever feasible (in many cases, abbreviations and technical terms are used which aren’t English).
Open source projects with a global audience are encouraged to adopt a similar policy.
Imports
- Imports should usually be on separate lines:
It’s okay to say this though:
Imports should be grouped in the following order:
- Standard library imports.
- Related third party imports.
- Local application/library specific imports.
You should put a blank line between each group of imports.
However, explicit relative imports are an acceptable alternative to absolute imports, especially when dealing with complex package layouts where using absolute imports would be unnecessarily verbose:
Standard library code should avoid complex package layouts and always use absolute imports.
If this spelling causes local name clashes, then spell them explicitly:
and use “myclass.MyClass” and “foo.bar.yourclass.YourClass”.
When republishing names this way, the guidelines below regarding public and internal interfaces still apply.
Module Level Dunder Names
Module level “dunders” (i.e. names with two leading and two trailing underscores) such as __all__ , __author__ , __version__ , etc. should be placed after the module docstring but before any import statements except from __future__ imports. Python mandates that future-imports must appear in the module before any other code except docstrings:
String Quotes
In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.
For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257.
Whitespace in Expressions and Statements
Pet Peeves
Avoid extraneous whitespace in the following situations:
-
Immediately inside parentheses, brackets or braces:
Other Recommendations
- Avoid trailing whitespace anywhere. Because it’s usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker. Some editors don’t preserve it and many projects (like CPython itself) have pre-commit hooks that reject it.
- Always surround these binary operators with a single space on either side: assignment ( = ), augmented assignment ( += , -= etc.), comparisons ( == , < , > , != , <> , <= , >= , in , not in , is , is not ), Booleans ( and , or , not ).
- If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator:
When combining an argument annotation with a default value, however, do use spaces around the = sign:
When to Use Trailing Commas
Trailing commas are usually optional, except they are mandatory when making a tuple of one element. For clarity, it is recommended to surround the latter in (technically redundant) parentheses:
When trailing commas are redundant, they are often helpful when a version control system is used, when a list of values, arguments or imported items is expected to be extended over time. The pattern is to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line. However it does not make sense to have a trailing comma on the same line as the closing delimiter (except in the above case of singleton tuples):
Comments
Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!
Comments should be complete sentences. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).
Block comments generally consist of one or more paragraphs built out of complete sentences, with each sentence ending in a period.
You should use one or two spaces after a sentence-ending period in multi-sentence comments, except after the final sentence.
Ensure that your comments are clear and easily understandable to other speakers of the language you are writing in.
Python coders from non-English speaking countries: please write your comments in English, unless you are 120% sure that the code will never be read by people who don’t speak your language.
Block Comments
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).
Paragraphs inside a block comment are separated by a line containing a single # .
Inline Comments
Use inline comments sparingly.
An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.
Inline comments are unnecessary and in fact distracting if they state the obvious. Don’t do this:
But sometimes, this is useful:
Documentation Strings
Conventions for writing good documentation strings (a.k.a. “docstrings”) are immortalized in PEP 257.
-
Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line. describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself:
Naming Conventions
The naming conventions of Python’s library are a bit of a mess, so we’ll never get this completely consistent – nevertheless, here are the currently recommended naming standards. New modules and packages (including third party frameworks) should be written to these standards, but where an existing library has a different style, internal consistency is preferred.
Overriding Principle
Names that are visible to the user as public parts of the API should follow conventions that reflect usage rather than implementation.
Descriptive: Naming Styles
There are a lot of different naming styles. It helps to be able to recognize what naming style is being used, independently from what they are used for.
The following naming styles are commonly distinguished:
- b (single lowercase letter)
- B (single uppercase letter)
- lowercase
- lower_case_with_underscores
- UPPERCASE
- UPPER_CASE_WITH_UNDERSCORES
- CapitalizedWords (or CapWords, or CamelCase – so named because of the bumpy look of its letters [4]). This is also sometimes known as StudlyCaps.
Note: When using acronyms in CapWords, capitalize all the letters of the acronym. Thus HTTPServerError is better than HttpServerError.
There’s also the style of using a short unique prefix to group related names together. This is not used much in Python, but it is mentioned for completeness. For example, the os.stat() function returns a tuple whose items traditionally have names like st_mode , st_size , st_mtime and so on. (This is done to emphasize the correspondence with the fields of the POSIX system call struct, which helps programmers familiar with that.)
The X11 library uses a leading X for all its public functions. In Python, this style is generally deemed unnecessary because attribute and method names are prefixed with an object, and function names are prefixed with a module name.
In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):
- _single_leading_underscore : weak “internal use” indicator. E.g. from M import * does not import objects whose names start with an underscore.
- single_trailing_underscore_ : used by convention to avoid conflicts with Python keyword, e.g.
Prescriptive: Naming Conventions
Names to Avoid
Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names.
In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use ‘l’, use ‘L’ instead.
ASCII Compatibility
Identifiers used in the standard library must be ASCII compatible as described in the policy section of PEP 3131.
Package and Module Names
Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket ).
Class Names
Class names should normally use the CapWords convention.
The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable.
Note that there is a separate convention for builtin names: most builtin names are single words (or two words run together), with the CapWords convention used only for exception names and builtin constants.
Type Variable Names
Names of type variables introduced in PEP 484 should normally use CapWords preferring short names: T , AnyStr , Num . It is recommended to add suffixes _co or _contra to the variables used to declare covariant or contravariant behavior correspondingly:
Exception Names
Because exceptions should be classes, the class naming convention applies here. However, you should use the suffix “Error” on your exception names (if the exception actually is an error).
Global Variable Names
(Let’s hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.
Modules that are designed for use via from M import * should use the __all__ mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are “module non-public”).
Function and Variable Names
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Variable names follow the same convention as function names.
mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility.
Function and Method Arguments
Always use self for the first argument to instance methods.
Always use cls for the first argument to class methods.
If a function argument’s name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is better than clss . (Perhaps better is to avoid such clashes by using a synonym.)
Method Names and Instance Variables
Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
Use one leading underscore only for non-public methods and instance variables.
To avoid name clashes with subclasses, use two leading underscores to invoke Python’s name mangling rules.
Python mangles these names with the class name: if class Foo has an attribute named __a , it cannot be accessed by Foo.__a . (An insistent user could still gain access by calling Foo._Foo__a .) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.
Note: there is some controversy about the use of __names (see below).
Constants
Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL .
Designing for Inheritance
Always decide whether a class’s methods and instance variables (collectively: “attributes”) should be public or non-public. If in doubt, choose non-public; it’s easier to make it public later than to make a public attribute non-public.
Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backwards incompatible changes. Non-public attributes are those that are not intended to be used by third parties; you make no guarantees that non-public attributes won’t change or even be removed.
We don’t use the term “private” here, since no attribute is really private in Python (without a generally unnecessary amount of work).
Another category of attributes are those that are part of the “subclass API” (often called “protected” in other languages). Some classes are designed to be inherited from, either to extend or modify aspects of the class’s behavior. When designing such a class, take care to make explicit decisions about which attributes are public, which are part of the subclass API, and which are truly only to be used by your base class.
With this in mind, here are the Pythonic guidelines:
- Public attributes should have no leading underscores.
- If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling. (However, notwithstanding this rule, ‘cls’ is the preferred spelling for any variable or argument which is known to be a class, especially the first argument to a class method.)
Note 1: See the argument name recommendation above for class methods.
Note 1: Try to keep the functional behavior side-effect free, although side-effects such as caching are generally fine.
Note 2: Avoid using properties for computationally expensive operations; the attribute notation makes the caller believe that access is (relatively) cheap.
Note 1: Note that only the simple class name is used in the mangled name, so if a subclass chooses both the same class name and attribute name, you can still get name collisions.
Note 2: Name mangling can make certain uses, such as debugging and __getattr__() , less convenient. However the name mangling algorithm is well documented and easy to perform manually.
Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.
Public and Internal Interfaces
Any backwards compatibility guarantees apply only to public interfaces. Accordingly, it is important that users be able to clearly distinguish between public and internal interfaces.
Documented interfaces are considered public, unless the documentation explicitly declares them to be provisional or internal interfaces exempt from the usual backwards compatibility guarantees. All undocumented interfaces should be assumed to be internal.
To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute. Setting __all__ to an empty list indicates that the module has no public API.
Even with __all__ set appropriately, internal interfaces (packages, modules, classes, functions, attributes or other names) should still be prefixed with a single leading underscore.
An interface is also considered internal if any containing namespace (package, module or class) is considered internal.
Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module’s API, such as os.path or a package’s __init__ module that exposes functionality from submodules.
Programming Recommendations
- Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such).
For example, do not rely on CPython’s efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn’t present at all in implementations that don’t use refcounting. In performance sensitive parts of the library, the ».join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.
Also, beware of writing if x when you really mean if x is not None – e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
To minimize the effort involved, the functools.total_ordering() decorator provides a tool to generate missing comparison methods.
PEP 207 indicates that reflexivity rules are assumed by Python. Thus, the interpreter may swap y > x with x < y , y >= x with x <= y , and may swap the arguments of x == y and x != y . The sort() and min() operations are guaranteed to use the < operator and the max() function uses the > operator. However, it is best to implement all six operations so that confusion doesn’t arise in other contexts.
The first form means that the name of the resulting function object is specifically ‘f’ instead of the generic ‘<lambda>’. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)
Design exception hierarchies based on the distinctions that code catching the exceptions is likely to need, rather than the locations where the exceptions are raised. Aim to answer the question “What went wrong?” programmatically, rather than only stating that “A problem occurred” (see PEP 3151 for an example of this lesson being learned for the builtin exception hierarchy)
Class naming conventions apply here, although you should add the suffix “Error” to your exception classes if the exception is an error. Non-error exceptions that are used for non-local flow control or other forms of signaling need no special suffix.
When deliberately replacing an inner exception (using raise X from None ), ensure that relevant details are transferred to the new exception (such as preserving the attribute name when converting KeyError to AttributeError, or embedding the text of the original exception in the new exception message).
A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException: ).
A good rule of thumb is to limit use of bare ‘except’ clauses to two cases: