PEP: 8

Title: Style Guide for Python Code

Introduction

이 λ¬Έμ„œλŠ” κΈ°λ³Έ Python 배포판의 ν‘œμ€€ 라이브러리λ₯Ό κ΅¬μ„±ν•˜λŠ” Python μ½”λ“œμ— λŒ€ν•œ μ½”λ”© κ·œμΉ™μ„ μ œκ³΅ν•©λ‹ˆλ‹€. Python의 C κ΅¬ν˜„μ—μ„œ C μ½”λ“œμ— λŒ€ν•œ μŠ€νƒ€μΌ 지침을 μ„€λͺ…ν•˜λŠ” λ™λ°˜μž 정보 PEPλ₯Ό μ°Έμ‘°ν•˜μ‹­μ‹œμ˜€ .

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].

이 μŠ€νƒ€μΌ κ°€μ΄λ“œλŠ” μΆ”κ°€ κ·œμΉ™μ΄ μ‹λ³„λ˜κ³  κ³Όκ±° κ·œμΉ™μ΄ μ–Έμ–΄ 자체의 λ³€κ²½μœΌλ‘œ 인해 μ“Έλͺ¨μ—†κ²Œ 됨에 따라 μ‹œκ°„μ΄ 지남에 따라 λ°œμ „ν•©λ‹ˆλ‹€.

λ§Žμ€ ν”„λ‘œμ νŠΈμ—λŠ” 자체 μ½”λ”© μŠ€νƒ€μΌ 지침이 μžˆμŠ΅λ‹ˆλ‹€. 좩돌이 μžˆλŠ” 경우 ν•΄λ‹Ή ν”„λ‘œμ νŠΈμ— λŒ€ν•œ ν•΄λ‹Ή ν”„λ‘œμ νŠΈλ³„ κ°€μ΄λ“œκ°€ μš°μ„ ν•©λ‹ˆλ‹€.

어리석은 일관성은 μž‘μ€ 마음의 ν™‰κ³ λΈ”λ¦°μž…λ‹ˆλ‹€.

Guido의 핡심 톡찰λ ₯ 쀑 ν•˜λ‚˜λŠ” μ½”λ“œκ°€ μž‘μ„±λœ 것보닀 훨씬 더 자주 μ½νžŒλ‹€λŠ” κ²ƒμž…λ‹ˆλ‹€. 여기에 제곡된 지침은 μ½”λ“œμ˜ 가독성을 κ°œμ„ ν•˜κ³  κ΄‘λ²”μœ„ν•œ Python μ½”λ“œμ—μ„œ 일관성을 μœ μ§€ν•˜κΈ° μœ„ν•œ κ²ƒμž…λ‹ˆλ‹€. PEP 20 이 λ§ν–ˆλ“― 이 "가독성이 μ€‘μš”ν•©λ‹ˆλ‹€".

μŠ€νƒ€μΌ κ°€μ΄λ“œλŠ” 일관성에 κ΄€ν•œ κ²ƒμž…λ‹ˆλ‹€. 이 μŠ€νƒ€μΌ κ°€μ΄λ“œμ™€μ˜ 일관성이 μ€‘μš”ν•©λ‹ˆλ‹€. ν”„λ‘œμ νŠΈ λ‚΄ 일관성이 더 μ€‘μš”ν•©λ‹ˆλ‹€. ν•˜λ‚˜μ˜ λͺ¨λ“ˆ λ˜λŠ” κΈ°λŠ₯ λ‚΄μ—μ„œ 일관성이 κ°€μž₯ μ€‘μš”ν•©λ‹ˆλ‹€.

κ·ΈλŸ¬λ‚˜ 일관성이 μ—†μ–΄μ•Ό ν•  λ•Œλ₯Ό μ•Œμ•„μ•Ό ν•©λ‹ˆλ‹€. λ•Œλ‘œλŠ” μŠ€νƒ€μΌ κ°€μ΄λ“œ ꢌμž₯ 사항이 μ μš©λ˜μ§€ μ•Šμ„ 수 μžˆμŠ΅λ‹ˆλ‹€. μ˜μ‹¬μŠ€λŸ¬μš΄ 경우 μ΅œμ„ μ˜ νŒλ‹¨μ„ μ‚¬μš©ν•˜μ‹­μ‹œμ˜€. λ‹€λ₯Έ 예λ₯Ό 보고 κ°€μž₯ 잘 λ³΄μ΄λŠ” 것을 κ²°μ •ν•˜μ‹­μ‹œμ˜€. 그리고 μ£Όμ €ν•˜μ§€ 말고 λ¬Όμ–΄λ³΄μ„Έμš”!

특히: 이 PEPλ₯Ό μ€€μˆ˜ν•˜κΈ° μœ„ν•΄ 이전 λ²„μ „κ³Όμ˜ ν˜Έν™˜μ„±μ„ μ€‘λ‹¨ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€!

νŠΉμ • 지침을 λ¬΄μ‹œν•΄μ•Ό ν•˜λŠ” λ‹€λ₯Έ 쒋은 이유:

  1. κ°€μ΄λ“œλΌμΈμ„ μ μš©ν•˜λ©΄ 이 PEPλ₯Ό λ”°λ₯΄λŠ” μ½”λ“œλ₯Ό μ½λŠ” 데 μ΅μˆ™ν•œ μ‚¬λžŒμ΄λΌλ„ μ½”λ“œμ˜ 가독성이 λ–¨μ–΄μ§‘λ‹ˆλ‹€.

  2. 그것을 κΉ¨λœ¨λ¦¬λŠ” μ£Όλ³€ μ½”λ“œμ™€ 일관성을 μœ μ§€ν•˜κΈ° μœ„ν•΄(역사적인 이유 λ•Œλ¬ΈμΌ 수 있음) – 이것은 λ˜ν•œ λ‹€λ₯Έ μ‚¬λžŒμ˜ 엉망진창을 정리할 수 μžˆλŠ” κΈ°νšŒμ΄κΈ°λ„ ν•©λ‹ˆλ‹€(μ§„μ •ν•œ XP μŠ€νƒ€μΌ).

  3. 문제의 μ½”λ“œλŠ” κ°€μ΄λ“œλΌμΈ λ„μž… μ΄μ „μ˜ μ½”λ“œμ΄κ³  ν•΄λ‹Ή μ½”λ“œλ₯Ό μˆ˜μ •ν•  λ‹€λ₯Έ μ΄μœ κ°€ μ—†κΈ° λ•Œλ¬Έμž…λ‹ˆλ‹€.

  4. μŠ€νƒ€μΌ κ°€μ΄λ“œμ—μ„œ ꢌμž₯ν•˜λŠ” κΈ°λŠ₯을 μ§€μ›ν•˜μ§€ μ•ŠλŠ” 이전 λ²„μ „μ˜ Pythonκ³Ό μ½”λ“œκ°€ 계속 ν˜Έν™˜λ˜μ–΄μ•Ό ν•˜λŠ” 경우.

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 [#fn-hi]_. 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::

# Correct:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# Add 4 spaces (an extra level of indentation) to distinguish arguments from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

::

# Wrong:

# Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# Further indentation required as indentation is not distinguishable.
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

The 4-space rule is optional for continuation lines.

Optional::

# Hanging indents *may* be indented to other than 4 spaces.
foo = long_function_name(
  var_one, var_two,
  var_three, var_four)

.. _multiline if-statements:

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::

# No extra indentation.
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    do_something()

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

(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::

my_list = [
    1, 2, 3,
    4, 5, 6,
    ]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )

or it may be lined up under the first character of the line that starts the multiline construct, as in::

my_list = [
    1, 2, 3,
    4, 5, 6,
]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
)

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::

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

(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::

# Wrong:
# operators sit far away from their operands
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)

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::

# Correct:
# easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

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ΜΉΜ²ȏ̼̘ 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

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::

"""This is the example module.

This module does stuff.
"""

from __future__ import barry_as_FLUFL

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'Cardinal Biggles'

import os
import sys

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:

Other Recommendations

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::

# Correct:
FILES = ('setup.cfg',)

::

# Wrong:
FILES = 'setup.cfg',

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)::

# Correct:
FILES = [
    'setup.cfg',
    'tox.ini',
    ]
initialize(FILES,
           error=True,
           )

::

# Wrong:
FILES = ['setup.cfg', 'tox.ini',]
initialize(FILES, error=True,)

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 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::

x = x + 1                 # Increment x

But sometimes, this is useful::

x = x + 1                 # Compensate for border

Documentation Strings

Conventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in :pep:257.

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:

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):

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 :pep:policy section <3131#policy-specification> 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::

    from typing import TypeVar

    VT_co = TypeVar('VT_co', covariant=True)
    KT_contra = TypeVar('KT_contra', contravariant=True)

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 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

Function Annotations

With the acceptance of :pep:484, the style rules for function annotations have changed.

Variable Annotations

:pep:526 introduced variable annotations. The style recommendations for them are similar to those on function annotations described above:

.. rubric:: Footnotes

.. [#fn-hi] Hanging indentation is a type-setting style where all the lines in a paragraph are indented except the first line. In the context of Python, the term is used to describe a style where the opening parenthesis of a parenthesized statement is the last non-whitespace character of the line, with subsequent lines being indented until the closing parenthesis.

References

.. [2] Barry's GNU Mailman style guide http://barry.warsaw.us/software/STYLEGUIDE.txt

.. [3] Donald Knuth's The TeXBook, pages 195 and 196.

.. [4] http://www.wikipedia.com/wiki/CamelCase

.. [5] Typeshed repo https://github.com/python/typeshed

Copyright

This document has been placed in the public domain.

.. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 coding: utf-8 End:

What Else?
inflearn react api server -50% 할인쿠폰: 20652-ab1f1cd4c373 buy me a coffee