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:
Name already in use
py_training_ru / lecture_08.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Лекция 8. Ввод-вывод в файлы. Конструкция with
Значки, используемые в тексте
- — отмечает, что высказывание не совсем верно, но будет уточнено позднее.
- ⭐ — выделяет определение нового понятия.
- ❗ — привлекает внимание к высказыванию.
- ☝️ — указывает на небольшое отступление от темы или уточнение.
- — индикатор традиций и договорённостей.
- ⚠️ — требуется осторожность: возможно, сложное высказывание.
Повторение терминов из седьмой лекции
- Конструкция try-except-else — синтаскическая конструкция (сложное утверждение), предназначенная для обработки исключений из блока try в блоках except и выполнения блока else в случае отсутствия ошибок.
- Утверждение raise — утверждение, дающее возможность непосредственно вызвать исключение в коде.
Что такое файл? С точки зрения Python, это объект файловой системы, поддерживающий потоковое чтение и запись.
Для того, чтобы начать работу с файлом (чтение или запись), необходимо открыть файл, с указанием вида работы.
Файл обычно идентифицируется именем, и Python также использует имя файла для его открытия, которое осуществляется встроенной функцией open() :
Функция open() принимает как минимум 1 аргумент — имя файла — и возвращает объект типа file (также встроенный в Python тип), с которым далее и ведётся работа. Вторым аргументом функции указывается способ работы, то есть чтение или запись; по умолчанию, файл открывается на чтение.
У объекта файла есть набор атрибутов и методов, которые в дальнейшем используются для работы с файлом.
Имя файла, связанного с объектом, доступно через атрибут file.name :
При отсутствии такого файла или невозможности открыть его (например, нет разрешений, либо файл является каталогом) возникнет исключение IOError .
Чтобы прочитать содержимое файла, используется метод file.read() . Он возвращает Python-строку ( str ) состоящую из всего содержимого файла, либо если передать ему 1 аргумент — целое число N, то строка будет состоять из первых N байт файла (либо файла целиком, если его размер меньше N байт).
Можно написать программу из 2 строк, которая выведет собственный код, для этого достаточно сохранить её в файл например program1.py и написать:
Указатель позиции в файле
Если вызвать метод file.read() без аргументов более одного раза, то он вернёт пустую строку:
Объяснение этому таково. Файл можно представить как упорядоченную последовательность байт, каждый из которых имеет индекс, начиная с 0 (первый байт) и до «размер файла — 1». При чтении данных из файла, каждый байт условно по очереди передаётся в строку-результат, и индекс (указатель на текущий байт) увеличивается. По окончании чтения, индекс остаётся в том же месте, и следующее чтение начнётся с этого индекса. Если мы уже прочитали весь файл, то логично, что данных после текущего указателя уже нет.
Метод file.read() не только читает данные из файла, но и увеличивает указатель на кол-во прочитанных байт. Если в цикле читать из файла по одному байту, то каждый раз в результате чтения будет следующий байт, до тех пор, пока мы не достигнем конца файла.
Текстовые и бинарные файлы
Во многих системах файлы бывают двух «разновидностей»: текстовые и двоичные (бинарные). В общем любой файл можно считать бинарным, особенно если нам не требуется работать с файлом по частям. Если мы считываем весь файл в строку с помощью метода file.read() , то далее мы можем работать со строкой, полностью игнорируя вид файла.
Главное отличие этих видов в семантике доступа: для текстовых файлов имеет смысл построчный доступ, для бинарных — посимвольный или буферизованный.
С точки зрения пользователя, вид файла не всегда имеет значение, скажем, файл с данными xml или json по содержанию является текстовым, но едва ли имеет смысл обрабатывать его построчно, так как данные представляют собой единую структуру. В то же время файл типа doc для пользователя представляет двоичную кодировку текста.
Работа с текстовыми файлами
Типичным текстовым файлом является файл программы на Python. Для построчного чтения текстовых файлов существует метод file.readline() , который читает строку из файла и увеличивает указатель на длину прочитанной строки. При этом конец строки определяется настройками текущей ОС: для Linux концом строки служит символ перевода строки «\n» (или «\x0a» ), для Windows — последовательность «\r\n» (или «\x0d\x0a» ).
Этот метод удобно использовать в цикле while , опять же проверяя, что считанная строка не пустая. Также в этом методе можно задавать максимальную длину считываемой строки.
Для большего удобства построчного чтения файлов целиком, в цикле for мы можем использовать метод file.readlines() :
Или даже ещё проще:
Объект типа файл является итерируемым, как списки и строки, и итерируется по строкам, содержащимся в файле.
Работа с бинарными файлами
Для итеративной (поблочной) работы с бинарными файлами используется метод file.read(N) , где N — размер считываемого блока. Проверять, что достигнут конец файла, можно, сравнивая длину результата с N, либо также считывать до получения пустой строки.
У бинарных файлов есть ещё одно отличие: мы можем узнать, где сейчас указатель, и передвинуть указатель вручную на нужное место. (То есть, мы можем это делать и в текстовых файлах, но там это бессмысленно.) Для этого предназначены два соответствующих метода: file.tell() и file.seek() .
Первый возвращает индекс байта, на котором сейчас указатель; второй — принимает число-индекс в качестве аргумента и устанавливает указатель на этот индекс.
Таким образом, мы в теории сможем при достижении конца файла вернуть указатель на начало и прочитать содержимое заново. Впрочем, на практике это крайне редко используется.
Для разрешения записи в файл, как мы уже упомянули выше, необходимо сообщить функции open() , что мы открываем файл на запись. Режим работы с файлом передаётся вторым аргументом функции open() и представляет собой строку.
Запись может быть двух видов: перезапись (создание файла, если его ещё нет, либо пересоздание файла, если он уже есть) и дозапись (добавление в конец файла, если он есть, либо ошибка IOError в случае отсутствия).
Режим записи обозначается строкой «w» , режим добавления — строкой «a» .
Далее, собственно писать в файл можно исользуя метод file.write() , который принимает параметр — Python-строку с содержимым для записи. При записи, как и при чтении, указатель позиции в файле увеличивается на количество записанных байт.
Однако если просто записать в открытый файл, записанные данные не сохранятся. Для сохранения данных необходимо закрыть файл, это делается методом file.close() .
Примечание: файлы сами закрываются при выходе из программы, но крайне рекомендуется закрывать их вручную во избежание ошибок.
Смешанные режимы открытия файла
Возможно также открыть файл в режиме, совмещающем чтение и запись. Существует три таких режима:
- чтение с возможностью записи, режим «r+»
- перезапись с возможностью чтения, режим «w+»
- дозапись с возможностью чтения, режим «a+»
Они в целом соответствуют своим «основным» режимам.
Некоторые синтаксические конструкции, облегчающие работу с файлами
Представим себе ситуацию, что мы обрабатываем файл построчно и ищем какую-то строку, после которой дальнейшая обработка уже не имеет смысла. Используя цикл for , нам бы пришлось создавать переменную-флаг и «вхолостую» пробегать остаток файла, проверяя этот флаг в каждой итерации.
К счастью, в Python можно обойтись куда более простой конструкцией.
Утверждение break даёт команду немедленно выйти из цикла к следующему за ним утверждению, полностью пропустив оставшиеся итерации и также все утверждения, идущие в блоке кода цикла после break .
В данном случае будет выводиться на экран каждая строка до строки, содержащей «end», не включая её, потому что цикл закончится до вывода её на экран.
Утверждение break можно использовать не только в обработке файлов, и не только в цикле for : циклы while также поддерживают его. Но в любом другом блоке кода, который не относится к циклам, использование break является синтаксической ошибкой.
Утверждение continue является дополнением break : оно пропускает все следующие за ним утверждения в блоке кода цикла и переходит к следующей его итерации. В случае с циклом for это означает — к обработке следующего элемента (если он есть), в случае while — к следующей проверке условия.
Его удобно использовать, если нам нужно, наоборот, начать обработку файла с какой-то строки файла или пропустить обработку строки.
Этот код будет пропускать все строки файла до строки, содержащей «start», начиная с неё, он начнёт выводить все те строки, которые не содержат «skip».
Объект файла, будучи итерируемым объектом (типа контейнера) является ещё и так называемым контекстным менеджером.
Контекстный менеджер умеет автоматически выполнять некторые действия по окончанию выполнения определённого контекста, который задаётся конструкцией with :
БЛОК_КОДА в данном случае и является контекстом. Независимо от того, произошли ли ошибки в БЛОКе_КОДА, контекстный менеджер всегда выполнит завершающие действия, а именно для файлов — их закрытие.
Возьмём пример, использованный выше:
Его можно переписать так:
И файл автоматически будет закрыт по окончанию блока кода в with .
Записать в новый текстовый файл числа от 1 до 10 по одному в строке.
- в файл можно записать только строковые данные.
- В конец записываемой строки необходимо добавлять символы перевода строки, для Windows это последовательность «\r\n» .
Прочитать из записанного файла числа от 3 до 7 включительно, используя break и continue . В результате должен получиться список из 5 чисел.
8.1. Теория¶
Файлы используются программами для долговременного хранения информации, как необходимой для собственной работы (например, настройки), так и полученной во время ее исполнения (результаты вычислений и т.д.). Подавляющее большинство программ сегодня в том или ином виде используют файлы, сохраняя результаты работы между сеансами запуска.
8.1.1. Файлы и файловая система¶
Файл (англ. File) — именованная область данных на носителе информации.
Файлы хранятся в файловой системе — каталоге, определяющим способ организации, хранения и именования данных, а также задающем ограничения на формат и доступ к данным. На сегодняшний день наиболее популярными являются древовидные каталоги (также директории или папки) — файлы, содержащие записи о входящих в них файлах (Рисунок 8.1.1).

Рисунок 8.1.1 — Пример древовидной организации файловой системы в ОС Windows 6. ¶
Файловая система связывает носитель информации с одной стороны и программный интерфейс для доступа к файлам — с другой. Когда прикладная программа обращается к файлу, она не имеет никакого представления о том, каким образом расположена информация в конкретном файле, так же как и на каком физическом типе носителя (CD, жестком диске, магнитной ленте, блоке флеш-памяти или другом) он записан. Все, что знает программа — это имя файла, его размер и атрибуты (получая их от драйвера файловой системы). Именно файловая система устанавливает, где и как будет записан файл на физическом носителе (например, жестком диске) (Рисунок 8.1.2).

Рисунок 8.1.2 — Файловая система предоставляет интерфейс доступа к файлам для операционной системы 7 ¶
8.1.1.1. Свойства файла¶
Файл может обладать различным набором свойств в зависимости от файловой системы.
В большинстве файловых систем файл имеет следующие свойства:
имя и расширение (как правило, называемые просто именем вместе): например, моя_программа.py ;
дата/время (могут быть предусмотрены маркеры создания, модификации и последнего доступа);
атрибуты (скрытый, системный и др.) и права доступа.
Имя файла имеет определенные ограничения в зависимости от файловой и операционной системы, в частности, допустимые знаки и длину наименования. Расширение указывается после имени через точку, имея назначение, в основном, для ОС Windows, где определяет приложение для запуска файла.
В ОС Windows по умолчанию расширение файла скрыто от пользователя. Зачастую удобно «видеть» расширение, что можно включить в настройках: https://support.microsoft.com/ru-ru/kb/865219.
8.1.1.2. Путь к файлу: абсолютный и относительный¶
Для того, чтобы найти файл в файловой системе необходимо знать к нему путь — узлы дерева файловой системы, которые нужно пройти, чтобы до него добраться.
В операционных системах UNIX разделительным знаком при записи пути является / , в Windows — \ : эти знаки служат для разделения названия каталогов, составляющих путь к файлу.
Путь может быть:
абсолютным (полным): указывает на одно и то же место в файловой системе вне зависимости от текущей рабочей директории или других обстоятельств;
относительным: путь по отношению к текущему рабочему каталогу пользователя или активных приложений.
Примеры путей для ОС Windows и UNIX:
относительный: example1.py если текущий каталог C:\user\python\ ;
относительный: python\example1.py если текущий каталог C:\user\ ;
относительный: example1.py если текущий каталог /home/user/python/ ;
относительный: user/python/example1.py если текущий каталог /home/ .
См. более подробно про пути в разных операционных системах.
8.1.1.3. Операции с файлами¶
Все операции с файлами можно подразделить на 2 группы:
связанные с его открытием: открытие, закрытие файла, запись, чтение, перемещение по файлу и др.
выполняющиеся без его открытия: работа с файлом как элементом файловой системы — переименование, копирование, получение атрибутов и др.
При открытии файла, как правило, указываются:
после чего операционная система возвращает специальный дескриптор файла (идентификатор), однозначно определяющий, с каким файлом далее будут выполняться операции. После открытия доступен файловый указатель — число, определяющее позицию относительно начала файла.
8.1.1.4. Виды файлов¶
По способу организации файлы делятся на файлы с последовательным и произвольным доступом (Рисунок 8.1.3, Таблица 8.1.1).
Как организовать код в Python-проекте, чтобы потом не пожалеть
Python отличается от таких языков программирования, как C# или Java, заставляющих программиста давать классам имена, соответствующие именам файлов, в которых находится код этих классов.

Python — это самый гибкий язык программирования из тех, с которыми мне приходилось сталкиваться. А когда имеешь дело с чем-то «слишком гибким» — возрастает вероятность принятия неправильных решений.
Хотите держать все классы проекта в единственном файле main.py ? Да, это возможно.
Надо читать переменную окружения? Берите и читайте там, где это нужно.
Требуется модифицировать поведение функции? Почему бы не прибегнуть к декоратору!?
Применение многих идей, которые легко реализовать, может привести к негативным последствиям, к появлению кода, который очень тяжело поддерживать.
Но, если вы точно знаете о том, что делаете, последствия гибкости Python не обязательно окажутся плохими.
Здесь я собираюсь представить вашему вниманию рекомендации по организации Python-кода, которые сослужили мне хорошую службу, когда я работал в разных компаниях и взаимодействовал со многими людьми.
Структура Python-проекта
Сначала обратим внимание на структуру директорий проекта, на именование файлов и организацию модулей.
Рекомендую держать все файлы модулей в директории src , а тесты — в поддиректории tests этой директории:
Здесь <module> — это главный модуль проекта. Если вы не знаете точно — какой именно модуль у вас главный — подумайте о том, что пользователи проекта будут устанавливать командой pip install , и о том, как, по вашему мнению, должна выглядеть команда import для вашего модуля.
Часто имя главного модуля совпадает с именем всего проекта. Но это — не некое жёсткое правило.
Аргументы в пользу директории src
Я видел множество проектов, устроенных по-другому.
Например, в проекте может отсутствовать директория src , а все модули будут просто лежать в его корневой директории:
Уныло смотрится проект, в структуре которого нет никакого порядка из-за того, что его папки и файлы просто расположены по алфавиту, в соответствии с правилами сортировки объектов в IDE.
Главная причина, по которой рекомендуется пользоваться папкой src , заключается в том, чтобы активный код проекта был бы собран в одной директории, а настройки, параметры CI/CD, метаданные проекта находились бы за пределами этой директории.
Единственный минус такого подхода заключается в том, что, без дополнительных усилий, не получится воспользоваться в своём коде командой вида import module_a . Для этого потребуется кое-что сделать. Ниже мы поговорим о том, как решить эту проблему.
Именование файлов
Правило №1: тут нет файлов
Во-первых — в Python нет таких сущностей, как «файлы», и я заметил, что это — главный источник путаницы для новичков.
Если вы находитесь в директории, содержащей файл __init__.py , то это — директория, включающая в себя модули, а не файлы.
Рассматривайте каждый модуль, как пространство имён.
Я говорю о «пространстве имён», так как нельзя сказать с уверенностью — имеется ли в модуле множество функций и классов, или только константы. В нём может присутствовать практически всё что угодно, или лишь несколько сущностей пары видов.
Правило №2: если нужно — держите сущности в одном месте
Совершенно нормально, когда в одном модуле имеется несколько классов. Так и стоит организовывать код (но, конечно, только если классы связаны с модулем).
Выделяйте классы в отдельные модули только в том случае, если модуль становится слишком большим, или если его разные части направлены на решение различных задач.
Часто встречается мнение, что это — пример неудачного приёма работы. Те, кто так считают, находятся под влиянием опыта, полученного после использования других языков программирования, которые принуждают к другим решениям (например — это Java и C#).
Правило №3: давайте модулям имена, представляющие собой существительные во множественном числе
Давая модулям имена, следуйте общему правилу, в соответствии с которым эти имена должны представлять собой существительные во множественном числе. При этом они должны отражать особенности предметной области проекта.
Правда, у этого правила есть и исключение. Модули могут называться core , main.py или похожим образом, что указывает на то, что они представляют собой некую единичную сущность. Подбирая имена модулей, руководствуйтесь здравым смыслом, а если сомневаетесь — придерживайтесь вышеприведённого правила.
Реальный пример именования модулей
Вот мой проект — Google Maps Crawler, созданный в качестве примера.
Этот проект направлен на сбор данных из Google Maps с использованием Selenium и на их представление в виде, удобном для дальнейшей обработки (тут, если интересно, можно об этом почитать).
Вот текущее состояние дерева проекта (тут выделены исключения из правила №3):
Весьма естественным кажется такой импорт классов и функций:
Можно понять, что в exceptions может иметься как один, так и множество классов исключений.
Именование модулей существительными множественного числа отличается следующими приятными особенностями:
Модули не слишком «малы» (в том смысле, что предполагается, что один модуль может включать в себя несколько классов).
Их, если нужно, в любой момент можно разбить на более мелкие модули.
«Множественные» имена дают программисту сильное ощущение того, что он знает о том, что может быть внутри соответствующих модулей.
Именование классов, функций и переменных
Некоторые программисты считают, что давать сущностям имена — это непросто. Но если заранее определиться с правилами именования, эта задача становится уже не такой сложной.
Имена функций и методов должны быть глаголами
Функции и методы представляют собой действия, или нечто, выполняющее действия.
Функция или метод — это не просто нечто «существующее». Это — нечто «действующее».
Действия чётко определяются глаголами.
Вот — несколько удачных примеров из реального проекта, над которым я раньше работал:
А вот — несколько неудачных примеров:
Тут не очень ясно — возвращают ли функции объект, позволяющий выполнить обращение к API, или они сами выполняют какие-то действия, например — отправку письма.
Я могу представить себе такой сценарий использования функции с неудачным именем:
У рассмотренного правила есть и некоторые исключения:
Создание функции main() , которую вызовут в главной точке входа приложения — это хороший повод нарушить это правило.
Использование @property для того, чтобы обращаться с методом класса как с атрибутом, тоже допустимо.
Имена переменных и констант должны быть существительными
Имена переменных и констант всегда должны быть существительными и никогда — глаголами (это позволяет чётко отделить их от функций).
Вот примеры удачных имён:
Вот — неудачные имена:
А если переменная или константа представляют собой список или коллекцию — им подойдёт имя, представленное существительным во множественном числе:
Имена классов должны говорить сами за себя, но использование суффиксов — это нормально
Отдавайте предпочтение именам классов, понятным без дополнительных пояснений. При этом можно использовать и суффиксы, вроде Service , Strategy , Middleware , но — только в крайнем случае, когда они необходимы для чёткого описания цели существования класса.
Всегда давайте классам имена в единственном, а не во множественном числе. Имена во множественном числе напоминают имена коллекций элементов (например — если я вижу имя orders , то я полагаю, что это — список или итерируемый объект). Поэтому, выбирая имя класса, напоминайте себе, что после создания экземпляра класса в нашем распоряжении оказывается единственный объект.
Классы представляют собой некие сущности
Классы, представляющие нечто из бизнес-среды, должны называться в соответствии с названиями связанных с ними сущностей (и имена должны быть существительными!). Например — Order , Sale , Store , Restaurant и так далее.
Пример использования суффиксов
Представим, что надо создать класс, ответственный за отправку электронных писем. Если назвать его просто Email , цель его существования будет неясна.