ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python/PEP 8 – Style Guide for Python Code
    코딩/Python 2024. 3. 10. 02:47
    728x90

    파이썬 프로그래밍 가이드입니다.

    원본은 링크를 참조하세요.

    PEP 8 – Style Guide for Python Code

    Author:
    Guido van Rossum <guido at python.org>, Barry Warsaw <barry at python.org>, Alyssa Coghlan <ncoghlan at gmail.com>
    Status:
    Active
    Type:
    Process
    Created:
    05-Jul-2001
    Post-History:
    05-Jul-2001, 01-Aug-2013

    Introduction

    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.

    이 문서는 기본 Python 배포판의 표준 라이브러리를 구성하는 Python 코드에 대한 코딩 규칙을 제공합니다. Python의 C 구현에서 C 코드에 대한 스타일 지침을 설명하는 정보 제공 PEP를 참조하세요.

    이 문서와 PEP 257(Docstring Conventions)은 Guido의 원래 Python 스타일 가이드 에세이에서 수정되었으며 Barry의 스타일 가이드 [2]에서 일부 추가되었습니다.

    이 스타일 가이드는 추가 규칙이 식별되고 언어 자체의 변경으로 인해 과거 규칙이 더 이상 사용되지 않음에 따라 시간이 지남에 따라 발전합니다.

    많은 프로젝트에는 자체 코딩 스타일 지침이 있습니다. 충돌이 발생할 경우 해당 프로젝트에 대한 해당 프로젝트별 가이드가 우선적으로 적용됩니다.

    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:

    Guido의 주요 통찰력 중 하나는 코드가 작성된 것보다 훨씬 더 자주 읽힌다는 것입니다. 여기에 제공된 지침은 코드의 가독성을 향상시키고 광범위한 Python 코드에서 일관성을 유지하기 위한 것입니다. PEP 20에서 말했듯이 "가독성이 중요합니다".

    스타일 가이드는 일관성에 관한 것입니다. 이 스타일 가이드와의 일관성이 중요합니다. 프로젝트 내 일관성이 더 중요합니다. 하나의 모듈이나 기능 내에서 일관성이 가장 중요합니다.

    그러나 언제 일관성을 유지해야 하는지 알아두십시오. 때로는 스타일 가이드 권장 사항이 적용되지 않는 경우도 있습니다. 의심스러우면 최선의 판단을 내리십시오. 다른 예를 보고 무엇이 가장 좋아 보이는지 결정하세요. 그리고 주저하지 말고 물어보세요!

    특히: 단지 이 PEP를 준수하기 위해 이전 버전과의 호환성을 중단하지 마십시오!

    특정 지침을 무시해야 하는 다른 좋은 이유는 다음과 같습니다.

    • 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.
    • 지침을 적용하면 이 PEP를 따르는 코드를 읽는 데 익숙한 사람이라도 코드 읽기가 어려워집니다.
    • 이를 깨뜨리는 주변 코드와 일관성을 유지하기 위해(아마도 역사적인 이유로) – 이는 또한 다른 사람의 혼란을 정리할 수 있는 기회이기도 합니다(진정한 XP 스타일에서).
    • 문제의 코드는 지침이 도입되기 이전에 작성되었으며 해당 코드를 수정할 다른 이유가 없기 때문입니다.
    • 코드가 스타일 가이드에서 권장하는 기능을 지원하지 않는 이전 버전의 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 [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:

    들여쓰기 수준당 4개의 공백을 사용합니다.

    연속 줄은 괄호, 대괄호 및 중괄호 내부에 결합하는 Python의 암시적 줄을 사용하거나 내어쓰기[1]를 사용하여 래핑된 요소를 수직으로 정렬해야 합니다. 내어쓰기를 사용할 때는 다음 사항을 고려해야 합니다. 첫 번째 줄에는 인수가 없어야 하며 추가 들여쓰기를 사용하여 연속 줄과 명확하게 구분해야 합니다.

    # 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.
    # 인수를 나머지 인수와 구별하기 위해 4개의 공백(추가 들여쓰기 수준)을 추가합니다.
    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:

    연속 줄에서는 4칸 규칙이 선택 사항입니다.

    옵션:

    # Hanging indents *may* be indented to other than 4 spaces.
    # 내어쓰기는 4개의 공백이 아닌 다른 곳으로 들여쓰기될 수 있습니다.
    foo = long_function_name(
      var_one, var_two,
      var_three, var_four)

    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:

    if 문의 조건부 부분이 여러 줄에 걸쳐 작성해야 할 만큼 긴 경우 두 문자 키워드(예: if)와 단일 공백, 여는 괄호를 조합하면 자연스러운 조건문이 생성된다는 점에 주목할 필요가 있습니다. 여러 줄 조건문의 후속 줄에 대한 4칸 들여쓰기입니다. 이는 if 문 내부에 중첩된 들여쓰기된 코드 세트와 시각적 충돌을 일으킬 수 있으며, 자연스럽게 4개의 공백으로 들여쓰기됩니다. 이 PEP는 이러한 조건부 라인을 if 문 내부의 중첩된 스위트와 시각적으로 추가로 구별하는 방법(또는 여부)에 대해 명시적인 입장을 취하지 않습니다. 이 상황에서 허용되는 옵션은 다음을 포함하지만 이에 국한되지는 않습니다.

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

    공백이 선호되는 들여쓰기 방법입니다.

    탭은 이미 탭으로 들여쓰기된 코드와의 일관성을 유지하기 위해서만 사용해야 합니다.

    Python에서는 들여쓰기를 위해 탭과 공백을 혼합하는 것을 허용하지 않습니다.

    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:

    모든 줄을 최대 79자로 제한하세요.

    구조적 제한(독스트링 또는 주석)이 적은 긴 텍스트 블록을 흐르는 경우 행 길이는 72자로 제한되어야 합니다.

    필요한 편집기 창 너비를 제한하면 여러 파일을 나란히 열 수 있으며 인접한 열에 두 버전을 표시하는 코드 검토 도구를 사용할 때 잘 작동합니다.

    대부분의 도구에서 기본 래핑은 코드의 시각적 구조를 방해하여 이해하기 더 어렵게 만듭니다. 줄 바꿈 시 도구가 마지막 열에 마커 문자 모양을 배치하더라도 창 너비가 80으로 설정된 편집기에서 줄 바꿈을 방지하기 위해 제한이 선택됩니다. 일부 웹 기반 도구는 동적 줄 바꿈을 전혀 제공하지 않을 수 있습니다.

    일부 팀은 더 긴 라인 길이를 선호합니다. 이 문제에 대해 합의에 도달할 수 있는 팀에서 독점적으로 또는 주로 유지 관리하는 코드의 경우 주석과 독스트링이 여전히 72자로 래핑되어 있다면 줄 길이 제한을 최대 99자로 늘려도 괜찮습니다.

    Python 표준 라이브러리는 보수적이며 줄을 79자로 제한해야 합니다(독스트링/주석은 72자로).

    긴 줄을 래핑하는 데 선호되는 방법은 괄호, 대괄호 및 중괄호 안에 Python의 암시적 줄 연속을 사용하는 것입니다. 표현식을 괄호로 묶어 긴 줄을 여러 줄로 나눌 수 있습니다. 줄 연속을 위해 백슬래시를 사용하는 것보다 우선적으로 사용해야 합니다.

    백슬래시는 때때로 적절할 수도 있습니다. 예를 들어, 길고 여러 개의 with 문은 Python 3.10 이전에는 암시적 연속을 사용할 수 없었으므로 해당 경우에는 백슬래시가 허용되었습니다:

    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.

    (여러 줄의 with 문 들여쓰기에 대한 자세한 내용은 여러 줄의 if 문에 대한 이전 논의를 참조하세요.)

    또 다른 경우는 assert 문을 사용하는 경우입니다.

    이어지는 줄을 적절하게 들여쓰기했는지 확인하세요.

    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:

    이 가독성 문제를 해결하기 위해 수학자 및 출판사는 반대 규칙을 따릅니다. Donald Knuth는 그의 컴퓨터 및 조판 시리즈에서 전통적인 규칙을 다음과 같이 설명합니다. "단락 내의 수식은 항상 이진 연산 및 관계 다음에 깨지지만 표시된 수식은 항상 이진 연산 전에 깨집니다." [3]

    수학의 전통을 따르면 일반적으로 더 읽기 쉬운 코드가 생성됩니다.

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

    Python 코드에서는 규칙이 로컬에서 일관되는 한 이항 연산자 앞이나 뒤에 중단하는 것이 허용됩니다. 새로운 코드에는 Knuth의 스타일이 제안됩니다.

    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.

    최상위 함수 및 클래스 정의를 두 개의 빈 줄로 묶습니다.

    클래스 내부의 메서드 정의는 단일 빈 줄로 둘러싸여 있습니다.

    관련 기능 그룹을 구분하기 위해 여분의 빈 줄을 (아껴서) 사용할 수 있습니다. 관련된 단일 라이너 묶음(예: 더미 구현 세트) 사이에서는 빈 줄을 생략할 수 있습니다.

    함수에서 논리 섹션을 나타내기 위해 빈 줄을 드물게 사용하십시오.

    Python은 control-L(^L) 형식 피드 문자를 공백으로 허용합니다. 많은 도구는 이러한 문자를 페이지 구분 기호로 취급하므로 이를 사용하여 파일의 관련 섹션 페이지를 구분할 수 있습니다. 일부 편집자와 웹 기반 코드 뷰어는 control-L을 양식 피드로 인식하지 못하고 그 자리에 다른 문자 모양을 표시할 수 있습니다.

    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.

    핵심 Python 배포판의 코드는 항상 UTF-8을 사용해야 하며 인코딩 선언이 있어서는 안 됩니다.

    표준 라이브러리에서는 UTF-8이 아닌 인코딩을 테스트 목적으로만 사용해야 합니다. 비ASCII 문자는 되도록이면 장소와 사람 이름을 표시할 때만 사용하십시오. 비ASCII 문자를 데이터로 사용하는 경우 z̯̯͡a̧͎̺l̡͓̫g̹̲o̡̼̘ 및 바이트 순서 표시와 같은 시끄러운 유니코드 문자를 사용하지 마세요.

    Python 표준 라이브러리의 모든 식별자는 ASCII 전용 식별자를 사용해야 하며, 가능할 때마다 영어 단어를 사용해야 합니다(대부분의 경우 영어가 아닌 약어 및 기술 용어가 사용됩니다).

    전 세계를 대상으로 하는 오픈 소스 프로젝트도 유사한 정책을 채택하는 것이 좋습니다.

    Imports

    Imports should usually be on separate lines:

    Import는 일반적으로 별도의 줄에 있어야 합니다.

    # Correct:
    import os
    import sys
    # Wrong:
    import sys, os

    It’s okay to say this though:

    그래도 이렇게 해도 괜찮습니다.

    # Correct:
    from subprocess import Popen, PIPE

    Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

    You should put a blank line between each group of imports.

    Imports should be grouped in the following order:

    • Standard library imports.
    • Related third party imports.
    • Local application/library specific imports.

    Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path):

    Import는 항상 파일 상단, 모듈 주석 및 독스트링 바로 뒤, 모듈 전역 및 상수 앞에 배치됩니다.

    Import는 다음 순서로 그룹화되어야 합니다.

    각 Import 그룹 사이에 빈 줄을 넣어야 합니다.

    • 표준 라이브러리 가져오기.
    • 관련 제3자 import.
    • 로컬 애플리케이션/라이브러리별 가져오기.

    Absolute imports를 권장합니다. Import 시스템이 잘못 구성된 경우(예: 패키지 내부 디렉터리가 sys.path로 끝나는 경우) 일반적으로 더 읽기 쉽고 더 잘 동작하는 경향이 있기 때문입니다(또는 최소한 더 나은 오류 메시지를 제공하는 경우).

    Absolute import를 권장합니다. 만일 임포트 시스템이 부적절하게 구성되었다면(패키지 안의 디렉토리가 sys.path에서 끝내가 되는 것처럼) 더 읽기 쉽고 더 나은 동작을 하는 경향이 있기 때문입니다(또는 최소한 더 나은 에러 메시지를 냅니다).

    import mypkg.sibling
    from mypkg import sibling
    from mypkg.sibling import example

    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:

    그러나 명시적 상대 가져오기는 절대 가져오기의 대안으로 허용되며, 특히 절대 가져오기를 사용하는 것이 불필요하게 장황한 복잡한 패키지 레이아웃을 처리할 때 더욱 그렇습니다.

    from . import sibling
    from .sibling import example

    Standard library code should avoid complex package layouts and always use absolute imports.

    When importing a class from a class-containing module, it’s usually okay to spell this:

    표준 라이브러리 코드는 복잡한 패키지 레이아웃을 피하고 항상 절대 가져오기를 사용해야 합니다.

    클래스가 포함된 모듈에서 클래스를 가져올 때 일반적으로 다음과 같이 철자를 쓰는 것이 좋습니다.

    from myclass import MyClass
    from foo.bar.yourclass import YourClass

    If this spelling causes local name clashes, then spell them explicitly:

    이 철자로 인해 로컬 이름 충돌이 발생하는 경우 명시적으로 철자를 지정하세요.

    import myclass
    import foo.bar.yourclass

    and use myclass.MyClass and foo.bar.yourclass.YourClass.

    Wildcard imports (from <module> import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn’t known in advance).

    When republishing names this way, the guidelines below regarding public and internal interfaces still apply.

    myclass.MyClass 및 foo.bar.yourclass.YourClass를 사용하세요.

    와일드카드 import(from <module> import *)는 네임스페이스에 어떤 이름이 있는지 불분명하게 만들어 판독기와 많은 자동화 도구 모두를 혼란스럽게 하기 때문에 피해야 합니다. 와일드카드 가져오기에 대한 하나의 방어 가능한 사용 사례가 있습니다. 이는 내부 인터페이스를 공개 API의 일부로 다시 게시하는 것입니다(예를 들어, 선택적 가속기 모듈의 정의와 정확히 어떤 정의가 인터페이스의 순수 Python 구현을 덮어쓰는지 덮어쓴 내용은 미리 알 수 없습니다).

    이런 방식으로 이름을 다시 게시하는 경우 공개 및 내부 인터페이스에 관한 아래 지침이 계속 적용됩니다.

    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:

    __all__, __author__, __version__ 등과 같은 모듈 수준 "dunders"(즉, 앞에 두 개의 밑줄과 두 개의 뒤에 밑줄이 있는 이름)는 모듈 독스트링 뒤, __future__부터의 import를 제외한 모든 import 문 앞에 배치되어야 합니다. Python에서는 future-import가 모듈에서 독스트링을 제외한 다른 코드보다 먼저 나타나야 한다고 규정합니다.

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

    Python에서는 작은따옴표로 묶인 문자열과 큰따옴표로 묶인 문자열이 동일합니다. 이 PEP는 이에 대한 권장 사항을 제시하지 않습니다. 규칙을 선택하고 이를 준수하세요. 그러나 문자열에 작은따옴표 또는 큰따옴표 문자가 포함된 경우 문자열에 백슬래시가 들어가지 않도록 다른 하나를 사용하세요. 가독성이 향상됩니다.

    삼중따옴표로 묶인 문자열의 경우 PEP 257의 독스트링 규칙과 일치하도록 항상 큰따옴표 문자를 사용하세요.

    Whitespace in Expressions and Statements

    Pet Peeves

    Avoid extraneous whitespace in the following situations:

    다음 상황에서는 불필요한 공백을 피하세요.

    Immediately inside parentheses, brackets or braces:

    괄호, 대괄호 또는 중괄호 바로 안에:

    # Correct:
    spam(ham[1], {eggs: 2})
    # Wrong:
    spam( ham[ 1 ], { eggs: 2 } )

    Between a trailing comma and a following close parenthesis:

    후행 쉼표와 다음의 닫는 괄호 사이:

    # Correct:
    foo = (0,)
    # Wrong:
    bar = (0, )

    Immediately before a comma, semicolon, or colon:

    쉼표, 세미콜론 또는 콜론 바로 앞:

    # Correct:
    if x == 4: print(x, y); x, y = y, x
    # Wrong:
    if x == 4 : print(x , y) ; x , y = y , x

    However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted, the space is omitted:

    그러나 슬라이스에서 콜론은 이항 연산자처럼 작동하며 양쪽에 동일한 양이 있어야 합니다(우선 순위가 가장 낮은 연산자로 처리). 확장된 슬라이스에서는 두 콜론에 동일한 간격이 적용되어야 합니다. 예외: 슬라이스 매개변수가 생략되면 공백도 생략됩니다.

    # Correct:
    ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
    ham[lower:upper], ham[lower:upper:], ham[lower::step]
    ham[lower+offset : upper+offset]
    ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
    ham[lower + offset : upper + offset]
    # Wrong:
    ham[lower + offset:upper + offset]
    ham[1: 9], ham[1 :9], ham[1:9 :3]
    ham[lower : : step]
    ham[ : upper]

    Immediately before the open parenthesis that starts the argument list of a function call:

    함수 호출의 인수 목록을 시작하는 여는 괄호 바로 앞:

    # Correct:
    spam(1)
    # Wrong:
    spam (1)

    Immediately before the open parenthesis that starts an indexing or slicing:

    인덱싱 또는 슬라이싱을 시작하는 여는 괄호 바로 앞:

    # Correct:
    dct['key'] = lst[index]
    # Wrong:
    dct ['key'] = lst [index]

    More than one space around an assignment (or other) operator to align it with another:

    다른 연산자와 정렬하기 위해 할당(또는 기타) 연산자 주위에 두 개 이상의 공백:

    # Correct:
    x = 1
    y = 2
    long_variable = 3
    # Wrong:
    x             = 1
    y             = 2
    long_variable = 3

    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:

    어디에서나 후행 공백을 피하십시오. 일반적으로 눈에 띄지 않기 때문에 혼란스러울 수 있습니다. 백슬래시 뒤에 공백과 개행 문자가 오면 줄 연속 표시로 간주되지 않습니다. 일부 편집자는 이를 보존하지 않으며 많은 프로젝트(CPython 자체와 같은)에는 이를 거부하는 사전 커밋 후크가 있습니다.

    다음 이항 연산자는 항상 양쪽에 단일 공백으로 묶습니다: 할당(=), 추가 할당(+=, -= 등), 비교(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 불리언(and, or, not).

    우선순위가 다른 연산자를 사용하는 경우 우선순위가 가장 낮은 연산자 주위에 공백을 추가하는 것이 좋습니다. 자신의 판단을 사용하십시오. 그러나 공백을 두 개 이상 사용하지 말고 이항 연산자의 양쪽에 항상 같은 양의 공백을 두십시오.

    # Correct:
    i = i + 1
    submitted += 1
    x = x*2 - 1
    hypot2 = x*x + y*y
    c = (a+b) * (a-b)
    # Wrong:
    i=i+1
    submitted +=1
    x = x * 2 - 1
    hypot2 = x * x + y * y
    c = (a + b) * (a - b)

    Function annotations should use the normal rules for colons and always have spaces around the -> arrow if present. (See Function Annotations below for more about function annotations.):

    함수 주석은 콜론에 대한 일반 규칙을 사용해야 하며 -> 화살표가 있는 경우 항상 주위에 공백이 있어야 합니다. (함수 주석에 대한 자세한 내용은 아래 함수 주석을 참조하세요.):

    # Correct:
    def munge(input: AnyStr): ...
    def munge() -> PosInt: ...
    # Wrong:
    def munge(input:AnyStr): ...
    def munge()->PosInt: ...

    Don’t use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter:

    키워드 인수를 표시하는 데 사용되거나 주석이 지정되지 않은 함수 매개변수의 기본값을 표시하는 데 사용되는 경우 = 기호 주위에 공백을 사용하지 마세요.

    # Correct:
    def complex(real, imag=0.0):
        return magic(r=real, i=imag)
    # Wrong:
    def complex(real, imag = 0.0):
        return magic(r = real, i = imag)

    When combining an argument annotation with a default value, however, do use spaces around the = sign:

    그러나 인수 주석을 기본값과 결합할 때는 = 기호 주위에 공백을 사용하십시오.

    # Correct:
    def munge(sep: AnyStr = None): ...
    def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...
    # Wrong:
    def munge(input: AnyStr=None): ...
    def munge(input: AnyStr, limit = 1000): ...

    Compound statements (multiple statements on the same line) are generally discouraged:

    복합문(같은 줄에 여러 문이 있는 경우)은 일반적으로 권장되지 않습니다.

    # Correct:
    if foo == 'blah':
        do_blah_thing()
    do_one()
    do_two()
    do_three()

    Rather not:

    오히려 안좋습니다.

    # Wrong:
    if foo == 'blah': do_blah_thing()
    do_one(); do_two(); do_three()

    While sometimes it’s okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines!

    Rather not:

    때로는 같은 줄에 작은 본문이 있는 if/for/while을 배치하는 것이 괜찮지만 여러 절이 있는 명령문에는 절대 이 작업을 수행하지 마십시오. 또한 긴 줄을 접는 것도 피하세요!

    오히려 안좋습니다.

    # Wrong:
    if foo == 'blah': do_blah_thing()
    for x in lst: total += x
    while t < 10: t = delay()

    Definitely not:

    이렇게 하지 마세요:

    # Wrong:
    if foo == 'blah': do_blah_thing()
    else: do_non_blah_thing()
    
    try: something()
    finally: cleanup()
    
    do_one(); do_two(); do_three(long, argument,
                                 list, like, this)
    
    if foo == 'blah': one(); two(); three()

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

    코드와 모순되는 주석은 주석이 없는 것보다 더 나쁩니다. 코드가 변경되면 항상 주석을 최신 상태로 유지하는 것을 최우선으로 생각하세요!

    주석은 완전한 문장이어야 합니다. 첫 번째 단어는 소문자로 시작하는 식별자가 아닌 한 대문자로 시작해야 합니다(식별자의 대소문자를 변경하지 마세요!).

    블록 주석은 일반적으로 완전한 문장으로 구성된 하나 이상의 단락으로 구성되며, 각 문장은 마침표로 끝납니다.

    여러 문장으로 구성된 주석에서는 마지막 문장 뒤를 제외하고 문장 종료 마침표 뒤에 공백을 1~2개 사용해야 합니다.

    귀하의 의견이 귀하가 작성하는 언어를 사용하는 다른 사용자가 명확하고 쉽게 이해할 수 있는지 확인하십시오.

    비영어권 국가의 Python 코더: 귀하의 언어를 사용하지 않는 사람들이 코드를 절대 읽지 않을 것이라고 120% 확신하지 않는 한 영어로 의견을 작성하십시오.

    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.

    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.

    PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself:

    좋은 문서 문자열(일명 "docstring") 작성에 대한 규칙은 PEP 257에서 불멸화되었습니다.

    모든 공용 모듈, 함수, 클래스 및 메소드에 대한 독스트링을 작성하십시오. 비공개 메소드에는 Docstring이 필요하지 않지만 메소드가 수행하는 작업을 설명하는 주석이 있어야 합니다. 이 주석은 정의 줄 뒤에 나타나야 합니다.

    PEP 257은 좋은 독스트링 규칙을 설명합니다. 가장 중요한 점은 여러 줄 독스트링을 끝내는 """가 한 줄에 단독으로 있어야 한다는 점입니다:

    """Return a foobang
    
    Optional plotz says to frobnicate the bizbaz first.

    For one liner docstrings, please keep the closing """ on the same line:

    하나의 라이너 독스트링의 경우, 같은 줄에 닫는 """를 유지하십시오:

    """
    """Return an ex-parrot."""

    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.

    Python 라이브러리의 명명 규칙은 약간 혼란스럽기 때문에 완전히 일관되게 유지될 수는 없습니다. 그럼에도 불구하고 현재 권장되는 명명 표준은 다음과 같습니다. 새로운 모듈과 패키지(타사 프레임워크 포함)는 이러한 표준에 따라 작성되어야 하지만 기존 라이브러리의 스타일이 다른 경우 내부 일관성이 선호됩니다.

    Overriding Principle

    Names that are visible to the user as public parts of the API should follow conventions that reflect usage rather than implementation.

    API의 공개 부분으로 사용자에게 표시되는 이름은 구현보다는 사용법을 반영하는 규칙을 따라야 합니다.

    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.

    • mixedCase (differs from CapitalizedWords by initial lowercase character!)
    • Capitalized_Words_With_Underscores (ugly!)
    • b(단일 소문자)
    • B(단일 대문자)
    • 소문자
    • lower_case_with_underscores
    • 대문자
    • UPPER_CASE_WITH_UNDERSCORES
    • CapitalizedWords(또는 CapWords 또는 CamelCase – 글자가 울퉁불퉁해 보이기 때문에 붙여진 이름입니다[4]). 이것은 때때로 StudlyCaps로도 알려져 있습니다.

    참고: CapWords에서 약어를 사용할 때 약어의 모든 문자를 대문자로 표시하십시오. 따라서 HTTPServerError는 HttpServerError보다 낫습니다.

    • mixedCase (초기 소문자로 CapitalizedWords와 다릅니다!)
    • Capitalized_Words_With_Underscores (못생긴!)

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

    관련 이름을 그룹화하기 위해 짧은 고유 접두사를 사용하는 스타일도 있습니다. 이것은 Python에서 많이 사용되지 않지만 완전성을 위해 언급됩니다. 예를 들어, os.stat() 함수는 항목이 전통적으로 st_mode, st_size, st_mtime 등과 같은 이름을 갖는 튜플을 반환합니다. (이는 POSIX 시스템 호출 구조체의 필드와의 일치성을 강조하기 위해 수행되며 프로그래머가 이에 익숙해지도록 돕습니다.)

    X11 라이브러리는 모든 공개 기능에 대해 선행 X를 사용합니다. Python에서는 특성 및 메서드 이름 앞에 객체가 붙고 함수 이름 앞에 모듈 이름이 붙기 때문에 이 스타일은 일반적으로 불필요한 것으로 간주됩니다.

    또한 선행 또는 후행 밑줄을 사용하는 다음과 같은 특수 형식이 인식됩니다(일반적으로 모든 대소문자 규칙과 결합될 수 있음).

    • _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. :
    • _single_leading_underscore: 약한 "내부 사용" 표시. 예: from M import *는 이름이 밑줄로 시작하는 객체를 가져오지 않습니다.
    • single_trailing_underscore_: Python 키워드와의 충돌을 피하기 위해 관례적으로 사용됩니다. :
    tkinter.Toplevel(master, class_='ClassName')
    • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
    • __double_leading_and_trailing_underscore__: “magic” objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.
    • __double_leading_underscore: 클래스 속성의 이름을 지정할 때 이름 변경을 호출합니다(FooBar 클래스 내에서 __boo는 _FooBar__boo가 됩니다. 아래 참조).
    • __double_leading_and_trailing_underscore__: 사용자 제어 네임스페이스에 있는 "마법의" 개체 또는 속성입니다. 예: __init__, __import__ 또는 __file__. 절대로 그런 이름을 만들어내지 마십시오. 문서화된 대로만 사용하십시오.

    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.

    </font>

    단일 문자 변수 이름으로 문자 'l'(소문자 el), 'O'(대문자 oh) 또는 'I'(대문자 eye)를 사용하지 마십시오.

    일부 글꼴에서는 이러한 문자가 숫자 1과 0과 구별되지 않습니다. 'l'을 사용하고 싶다면 대신 'L'을 사용하세요.

    ASCII Compatibility

    Identifiers used in the standard library must be ASCII compatible as described in the policy section of PEP 3131.

    표준 라이브러리에 사용되는 식별자는 PEP 3131의 정책 섹션에 설명된 대로 ASCII와 호환되어야 합니다.

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

    모듈 이름은 모두 소문자로 이루어져야 합니다. 가독성을 높이려면 모듈 이름에 밑줄을 사용할 수 있습니다. Python 패키지에는 모두 소문자로 된 짧은 이름이 있어야 하지만 밑줄 사용은 권장되지 않습니다.

    C 또는 C++로 작성된 확장 모듈에 더 높은 수준(예: 보다 객체 지향적인) 인터페이스를 제공하는 Python 모듈이 있는 경우 C/C++ 모듈 앞에 밑줄(예: _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.

    클래스 이름은 일반적으로 CapWords 규칙을 사용해야 합니다.

    인터페이스가 문서화되고 주로 호출 가능 항목으로 사용되는 경우 함수에 대한 명명 규칙을 대신 사용할 수 있습니다.

    내장 이름에는 별도의 규칙이 있습니다. 대부분의 내장 이름은 단일 단어(또는 두 단어가 함께 실행됨)이며 CapWords 규칙은 예외 이름과 내장 상수에만 사용됩니다.

    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:

    PEP 484에 도입된 유형 변수의 이름은 일반적으로 T, AnyStr, Num과 같은 짧은 이름을 선호하는 CapWords를 사용해야 합니다. 공변 또는 반공변 동작을 선언하는 데 사용되는 변수에 접미사 _co 또는 _contra를 추가하는 것이 좋습니다.

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

    예외는 클래스여야 하므로 여기에는 클래스 명명 규칙이 적용됩니다. 그러나 예외 이름에 접미사 "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”).

    (이러한 변수가 하나의 모듈 내에서만 사용되기를 바랍니다.) 규칙은 함수의 규칙과 거의 동일합니다.

    from M import *를 통해 사용하도록 설계된 모듈은 __all__ 메커니즘을 사용하여 전역 내보내기를 방지하거나 해당 전역에 밑줄을 접두사로 붙이는 이전 규칙을 사용해야 합니다(이러한 전역이 “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.

    함수 이름은 소문자여야 하며, 가독성을 높이기 위해 필요에 따라 단어를 밑줄로 구분해야 합니다.

    변수 이름은 함수 이름과 동일한 규칙을 따릅니다.

    mixedCase는 이전 버전과의 호환성을 유지하기 위해 이미 널리 사용되는 스타일(예: threading.py)에서만 허용됩니다.

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

    인스턴스 메소드의 첫 번째 인수에는 항상 self를 사용하십시오.

    클래스 메소드의 첫 번째 인수에는 항상 cls를 사용하십시오.

    함수 인수의 이름이 예약된 키워드와 충돌하는 경우 일반적으로 약어나 철자법 손상을 사용하는 것보다 후행 밑줄 하나를 추가하는 것이 더 좋습니다. 따라서 class_는 clss보다 낫습니다. (아마도 동의어를 사용하여 이러한 충돌을 피하는 것이 더 나을 것입니다.)

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

    함수 명명 규칙을 사용하십시오. 가독성을 높이기 위해 필요에 따라 단어를 밑줄로 구분하여 소문자로 사용하세요.

    비공개 메서드와 인스턴스 변수에 대해서만 앞에 밑줄을 하나만 사용하세요.

    하위 클래스와의 이름 충돌을 피하려면 앞에 두 개의 밑줄을 사용하여 Python의 이름 맹글링 규칙을 호출하십시오.

    Python은 이러한 이름을 클래스 이름으로 변경합니다. Foo 클래스에 __a라는 속성이 있으면 Foo.__a에서 액세스할 수 없습니다. (강력한 사용자는 Foo._Foo__a를 호출하여 여전히 액세스 권한을 얻을 수 있습니다.) 일반적으로 이중 선행 밑줄은 하위 클래스로 분류되도록 설계된 클래스의 속성과 이름 충돌을 피하기 위해서만 사용해야 합니다.

    참고: __name 사용에 대한 논란이 있습니다(아래 참조).

    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.

    상수는 일반적으로 모듈 수준에서 정의되며 단어를 구분하는 밑줄과 함께 모두 대문자로 작성됩니다. 예로는 MAX_OVERFLOW 및 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:

    클래스의 메서드와 인스턴스 변수(통칭하여 "속성")가 공개인지 비공개인지 항상 결정하세요. 확실하지 않은 경우 비공개를 선택하세요. 공개 속성을 비공개로 설정하는 것보다 나중에 공개로 설정하는 것이 더 쉽습니다.

    공개 속성은 이전 버전과 호환되지 않는 변경을 방지하겠다는 약속과 함께 클래스의 관련 없는 클라이언트가 사용할 것으로 예상하는 속성입니다. 비공개 속성은 제3자가 사용하도록 의도되지 않은 속성입니다. 비공개 속성이 변경되거나 제거되지 않을 것이라는 보장은 없습니다.

    여기서는 “private”이라는 용어를 사용하지 않습니다. 왜냐하면 Python에서는 (일반적으로 불필요한 작업량 없이) 실제로 비공개 속성이 없기 때문입니다.

    또 다른 속성 범주는 "하위 클래스 API"(다른 언어에서는 "보호됨"이라고도 함)의 일부인 속성입니다. 일부 클래스는 클래스 동작의 측면을 확장하거나 수정하기 위해 상속되도록 설계되었습니다. 이러한 클래스를 디자인할 때 어떤 속성이 공개인지, 어떤 속성이 하위 클래스 API의 일부인지, 어떤 속성이 기본 클래스에서만 사용되는지 명시적으로 결정하도록 주의하세요.

    이를 염두에 두고 Python 지침은 다음과 같습니다.

    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.

    For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods. Keep in mind that Python provides an easy path to future enhancement, should you find that a simple data attribute needs to grow functional behavior. In that case, use properties to hide functional implementation behind simple data attribute access syntax.

    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.

    If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python’s name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.

    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.

    공용 속성에는 선행 밑줄이 없어야 합니다.

    공개 속성 이름이 예약된 키워드와 충돌하는 경우 속성 이름에 단일 후행 밑줄을 추가하세요. 이는 약어나 손상된 철자보다 바람직합니다. (그러나 이 규칙에도 불구하고 'cls'는 클래스로 알려진 모든 변수나 인수, 특히 클래스 메서드의 첫 번째 인수에 대해 선호되는 철자법입니다.)

    참고 1: 클래스 메서드에 대해서는 위의 인수 이름 권장 사항을 참조하세요.

    간단한 공개 데이터 속성의 경우 복잡한 접근자/변경자 메서드 없이 속성 이름만 노출하는 것이 가장 좋습니다. Python은 기능적 동작을 성장시키기 위해 간단한 데이터 속성이 필요한 경우 향후 개선을 위한 쉬운 경로를 제공한다는 점을 명심하십시오. 이 경우 속성을 사용하여 간단한 데이터 속성 액세스 구문 뒤에 기능적 구현을 숨깁니다.

    참고 1: 캐싱과 같은 부작용은 일반적으로 괜찮지만 기능적 동작에 부작용이 없도록 유지하십시오.

    참고 2: 계산 비용이 많이 드는 작업에는 속성을 사용하지 마세요. 속성 표기법은 호출자가 액세스가 (상대적으로) 저렴하다고 믿게 만듭니다.

    클래스를 하위 클래스로 분류하고 하위 클래스에서 사용하지 않으려는 속성이 있는 경우 앞에 밑줄을 두 개 사용하고 뒤에 밑줄을 사용하지 않고 이름을 지정하는 것을 고려하세요. 이는 클래스 이름이 속성 이름으로 맹글링되는 Python의 이름 맹글링 알고리즘을 호출합니다. 이는 서브클래스에 실수로 동일한 이름의 속성이 포함될 경우 속성 이름 충돌을 방지하는 데 도움이 됩니다.

    참고 1: 잘못된 이름에는 단순한 클래스 이름만 사용되므로 하위 클래스가 동일한 클래스 이름과 속성 이름을 모두 선택하는 경우에도 이름 충돌이 발생할 수 있습니다.

    참고 2: 이름 맹글링은 디버깅 및 __getattr__()과 같은 특정 용도를 덜 편리하게 만들 수 있습니다. 그러나 이름 맹글링 알고리즘은 잘 문서화되어 있으며 수동으로 수행하기 쉽습니다.

    참고 3: 모든 사람이 이름 변경을 좋아하는 것은 아닙니다. 실수로 이름이 충돌하는 것을 방지해야 하는 필요성과 고급 호출자가 사용할 가능성이 있는 경우의 균형을 맞추십시오.

    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.

    이전 버전과의 호환성 보장은 공용 인터페이스에만 적용됩니다. 따라서 사용자가 공용 인터페이스와 내부 인터페이스를 명확하게 구분할 수 있는 것이 중요합니다.

    문서화된 인터페이스는 일반적인 이전 버전과의 호환성 보장에서 제외되는 잠정적 또는 내부 인터페이스로 명시적으로 선언되지 않는 한 공용으로 간주됩니다. 문서화되지 않은 모든 인터페이스는 내부 인터페이스로 간주되어야 합니다.

    자체 검사를 더 잘 지원하려면 모듈은 __all__ 속성을 사용하여 공개 API에서 이름을 명시적으로 선언해야 합니다. __all__을 빈 목록으로 설정하면 모듈에 공개 API가 없음을 나타냅니다.

    __all__을 적절하게 설정하더라도 내부 인터페이스(패키지, 모듈, 클래스, 함수, 속성 또는 기타 이름) 앞에는 밑줄 하나를 앞에 붙여야 합니다.

    포함된 네임스페이스(패키지, 모듈 또는 클래스)가 내부로 간주되는 경우 인터페이스도 내부로 간주됩니다.

    가져온 이름은 항상 구현 세부 사항으로 간주되어야 합니다. 다른 모듈은 os.path 또는 하위 모듈의 기능을 노출하는 패키지의 __init__ 모듈과 같이 포함 모듈 API의 명시적으로 문서화된 부분이 아닌 이상 가져온 이름에 대한 간접적인 액세스에 의존해서는 안 됩니다.

    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.

    Comparisons to singletons like None should always be done with is or is not, never the equality operators.

    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!

    Use is not operator rather than not ... is. While both expressions are functionally identical, the former is more readable and preferred:

    코드는 Python의 다른 구현(PyPy, Jython, IronPython, Cython, Psyco 등)에 불리하지 않는 방식으로 작성되어야 합니다.

    예를 들어, a += b 또는 a = a + b 형식의 명령문에 대해 CPython의 내부 문자열 연결의 효율적인 구현에 의존하지 마십시오. 이 최적화는 CPython에서도 취약하며(일부 유형에서만 작동) 참조 계산을 사용하지 않는 구현에서는 전혀 존재하지 않습니다. 라이브러리의 성능에 민감한 부분에서는 ''.join() 형식을 대신 사용해야 합니다. 이렇게 하면 다양한 구현에서 선형 시간에 연결이 발생합니다.

    None과 같은 싱글톤과의 비교는 항상 is 또는 is not을 사용하여 수행해야 하며, 동등 연산자를 사용해서는 안 됩니다.

    또한, 실제로 x가 None이 아닌 경우를 의미할 때 if x를 쓰는 것을 주의하세요. 기본값이 None인 변수나 인수가 다른 값으로 설정되었는지 테스트할 때. 다른 값에는 부울 컨텍스트에서 false일 수 있는 유형(예: 컨테이너)이 있을 수 있습니다!

    not ... is보다 not 연산자를 사용합니다. 두 표현 모두 기능적으로 동일하지만 전자가 더 읽기 쉽고 선호됩니다.

    # Correct:
    if foo is not None:
    # Wrong:
    if not foo is None:

    When implementing ordering operations with rich comparisons, it is best to implement all six operations (__eq__, __ne__, __lt__, __le__, __gt__, __ge__) rather than relying on other code to only exercise a particular comparison.

    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.

    Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier:

    다양한 비교 기능을 갖춘 순서 작업을 구현할 때 특정 비교만 실행하기 위해 다른 코드에 의존하기보다는 6개 작업(__eq__, __ne__, __lt__, __le__, __gt__, __ge__)을 모두 구현하는 것이 가장 좋습니다.

    관련된 노력을 최소화하기 위해 functools.total_ordering() 데코레이터는 누락된 비교 방법을 생성하는 도구를 제공합니다.

    PEP 207은 재귀성 규칙이 Python에서 가정됨을 나타냅니다. 따라서 인터프리터는 y > x를 x < y로, y >= x를 x <= y로 바꿀 수 있으며 x == y 및 x != y의 인수를 바꿀 수 있습니다. sort() 및 min() 작업은 < 연산자를 사용하고 max() 함수는 > 연산자를 사용합니다. 그러나 다른 상황에서 혼동이 발생하지 않도록 6가지 작업을 모두 구현하는 것이 가장 좋습니다.

    람다 식을 식별자에 직접 바인딩하는 할당 문 대신 항상 def 문을 사용하세요.

    # Correct:
    def f(x): return 2*x
    # Wrong:
    f = lambda x: 2*x

    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)

    Derive exceptions from Exception rather than BaseException. Direct inheritance from BaseException is reserved for exceptions where catching them is almost always the wrong thing to do.

    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.

    Use exception chaining appropriately. raise X from Y should be used to indicate explicit replacement without losing the original traceback.

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

    When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause:

    첫 번째 형식은 결과 함수 객체의 이름이 일반 '<lambda>' 대신 구체적으로 'f'임을 의미합니다. 이는 일반적으로 역추적 및 문자열 표현에 더 유용합니다. 대입문을 사용하면 람다 식이 명시적 def 문에 비해 제공할 수 있는 유일한 이점(즉, 더 큰 표현식 내에 포함될 수 있다는 점)이 제거됩니다.

    BaseException이 아닌 Exception에서 예외를 파생시킵니다. BaseException으로부터의 직접 상속은 예외를 포착하는 것이 거의 항상 잘못된 일인 예외를 위해 예약되어 있습니다.

    예외가 발생하는 위치가 아니라 예외를 포착하는 코드에 필요할 가능성이 있는 구별을 기반으로 예외 계층 구조를 설계합니다. “무엇이 잘못되었나요?”라는 질문에 답하는 것을 목표로 하세요. "문제가 발생했습니다"라고만 언급하는 것이 아니라 프로그래밍 방식으로 (내장 예외 계층 구조에 대해 학습하는 이 교훈의 예는 PEP 3151을 참조하세요)

    예외가 오류인 경우 예외 클래스에 접미사 "Error"를 추가해야 하지만 여기에는 클래스 명명 규칙이 적용됩니다. 비로컬 흐름 제어나 다른 형태의 신호 전달에 사용되는 오류가 아닌 예외에는 특별한 접미사가 필요하지 않습니다.

    예외 체인을 적절하게 사용하십시오. raise X from Y는 원래 역추적을 잃지 않고 명시적인 교체를 나타내기 위해 사용해야 합니다.

    의도적으로 내부 예외를 대체하는 경우(None에서 X 발생 사용) 관련 세부 정보가 새 예외로 전송되는지 확인하세요(예:

    KeyError를 AttributeError로 변환할 때 속성 이름을 유지하는 경우, 또는 초기 예외를 새로운 예외 메시지에 포함하려 할 때)

    예외를 포착할 때, 단지 Except: 절을 사용하는 대신 가능할 때마다 특정 예외를 언급하세요.

    try:
        import platform_specific_module
    except ImportError:
        platform_specific_module = None

    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:

    • If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
    • If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise. try...finally can be a better way to handle this case.

    When catching operating system errors, prefer the explicit exception hierarchy introduced in Python 3.3 over introspection of errno values.

    Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs:

    빈 except: 절은 SystemExit 및 KeyboardInterrupt 예외를 포착하여 Control-C로 프로그램을 중단하기 어렵게 만들고 다른 문제를 위장할 수 있습니다. 프로그램 오류를 알리는 모든 예외를 포착하려면 Exception:을 제외하고 사용합니다(빈 except는 except BaseException:과 동일합니다).

    경험에 따르면 'except' 절의 사용을 두 가지 경우로 제한하는 것이 좋습니다.

    • 예외 처리기가 역추적을 인쇄하거나 기록하는 경우; 적어도 사용자는 오류가 발생했다는 사실을 알게 될 것입니다.
    • 코드에서 일부 정리 작업을 수행해야 하지만 발생을 통해 예외가 위쪽으로 전파되도록 하는 경우입니다. try...finally가 이 사례를 처리하는 더 좋은 방법이 될 수 있습니다.

    운영 체제 오류를 포착할 때 errno 값을 검사하는 것보다 Python 3.3에 도입된 명시적 예외 계층 구조를 선호합니다.

    또한 모든 try/except 절에 대해 try 절을 필요한 최소 코드 양으로 제한하세요. 다시 말하지만, 이는 버그 마스킹을 방지합니다.

    # Correct:
    try:
        value = collection[key]
    except KeyError:
        return key_not_found(key)
    else:
        return handle_value(value)
    # Wrong:
    try:
        # Too broad!
        return handle_value(collection[key])
    except KeyError:
        # Will also catch KeyError raised by handle_value()
        # handler_value()에 의해 발생한 KeyError도 포착합니다.
        return key_not_found(key)

    When a resource is local to a particular section of code, use a with statement to ensure it is cleaned up promptly and reliably after use. A try/finally statement is also acceptable.

    Context managers should be invoked through separate functions or methods whenever they do something other than acquire and release resources:

    리소스가 특정 코드 섹션에 로컬인 경우 with 문을 사용하여 사용 후 신속하고 안정적으로 정리되도록 합니다. try/finally 문도 허용됩니다.

    컨텍스트 관리자는 리소스 획득 및 해제 이외의 작업을 수행할 때마다 별도의 함수나 메서드를 통해 호출되어야 합니다.

    # Correct:
    with conn.begin_transaction():
        do_stuff_in_transaction(conn)
    # Wrong:
    with conn:
        do_stuff_in_transaction(conn)

    The latter example doesn’t provide any information to indicate that the __enter__ and __exit__ methods are doing something other than closing the connection after a transaction. Being explicit is important in this case.

    Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable):

    후자의 예는 __enter____exit__ 메서드가 트랜잭션 후 연결을 닫는 것 이외의 작업을 수행하고 있음을 나타내는 정보를 제공하지 않습니다. 이 경우 명시적인 것이 중요합니다.

    반환문에 일관성을 유지하세요. 함수의 모든 return 문은 표현식을 반환해야 하거나 그 중 어느 것도 반환해서는 안 됩니다. return 문이 표현식을 반환하는 경우 값이 반환되지 않는 모든 return 문은 이를 명시적으로 return None으로 명시해야 하며 명시적인 return 문은 함수 끝에 있어야 합니다(도달 가능한 경우).

    # Correct:
    def foo(x):
        if x >= 0:
            return math.sqrt(x)
        else:
            return None
    
    def bar(x):
        if x < 0:
            return None
        return math.sqrt(x)
    # Wrong:
    def foo(x):
        if x >= 0:
            return math.sqrt(x)
    
    def bar(x):
        if x < 0:
            return
        return math.sqrt(x)

    Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes.

    startswith() and endswith() are cleaner and less error prone:

    문자열 슬라이싱 대신 ''.startswith() 및 ''.endswith()를 사용하여 접두사 또는 접미사를 확인하세요.

    startwith() 및 endwith()는 더 깔끔하고 오류 발생 가능성이 적습니다.

    # Correct:
    if foo.startswith('bar'):
    # Wrong:
    if foo[:3] == 'bar':

    Object type comparisons should always use isinstance() instead of comparing types directly:

    객체 유형 비교에서는 유형을 직접 비교하는 대신 항상 isinstance()를 사용해야 합니다.

    # Correct:
    if isinstance(obj, int):
    # Wrong:
    if type(obj) is type(1):

    For sequences, (strings, lists, tuples), use the fact that empty sequences are false:

    시퀀스(문자열, list, 튜플)의 경우 빈 시퀀스가 거짓이라는 사실을 사용하세요.

    # Correct:
    if not seq:
    if seq:
    # Wrong:
    if len(seq):
    if not len(seq):

    Don’t write string literals that rely on significant trailing whitespace. Such trailing whitespace is visually indistinguishable and some editors (or more recently, reindent.py) will trim them.

    Don’t compare boolean values to True or False using ==:

    상당한 후행 공백에 의존하는 문자열 리터럴을 작성하지 마세요. 이러한 후행 공백은 시각적으로 구별할 수 없으며 일부 편집자(또는 최근에는 reindent.py)가 이를 잘라냅니다.

    ==를 사용하여 부울 값을 True 또는 False와 비교하지 마세요.

    # Correct:
    if greeting:
    # Wrong:
    if greeting == True:

    Worse:

    나쁜 경우

    # Wrong:
    if greeting is True:

    Use of the flow control statements return/break/continue within the finally suite of a try...finally, where the flow control statement would jump outside the finally suite, is discouraged. This is because such statements will implicitly cancel any active exception that is propagating through the finally suite:

    흐름 제어 문이 finally 모음 외부로 이동하는 try...finally의 finally 모음 내에서 흐름 제어 문 return/break/continue를 사용하는 것은 권장되지 않습니다. 이는 이러한 문이 finally 모음을 통해 전파되는 모든 활성 예외를 암시적으로 취소하기 때문입니다.

    # Wrong:
    def foo():
        try:
            1 / 0
        finally:
            return 42

    Function Annotations

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

    PEP 484가 승인되면서 함수 주석에 대한 스타일 규칙이 변경되었습니다.

    Function annotations should use PEP 484 syntax (there are some formatting recommendations for annotations in the previous section).

    The experimentation with annotation styles that was recommended previously in this PEP is no longer encouraged.

    However, outside the stdlib, experiments within the rules of PEP 484 are now encouraged. For example, marking up a large third party library or application with PEP 484 style type annotations, reviewing how easy it was to add those annotations, and observing whether their presence increases code understandability.

    The Python standard library should be conservative in adopting such annotations, but their use is allowed for new code and for big refactorings.

    For code that wants to make a different use of function annotations it is recommended to put a comment of the form:

    함수 주석은 PEP 484 구문을 사용해야 합니다(이전 섹션에 주석에 대한 몇 가지 형식 권장 사항이 있습니다).

    이전에 이 PEP에서 권장되었던 주석 스타일 실험은 더 이상 권장되지 않습니다.

    그러나 이제 stdlib 외부에서 PEP 484 규칙 내의 실험이 권장됩니다. 예를 들어 PEP 484 스타일 유형 주석으로 대규모 타사 라이브러리 또는 애플리케이션을 마크업하고, 해당 주석을 추가하는 것이 얼마나 쉬운지 검토하고, 주석의 존재가 코드 이해성을 높이는지 관찰합니다.

    Python 표준 라이브러리는 이러한 주석을 채택하는 데 보수적이어야 하지만 새 코드와 대규모 리팩토링에는 해당 주석을 사용할 수 있습니다.

    함수 주석을 다르게 사용하려는 코드의 경우 다음 형식의 주석을 추가하는 것이 좋습니다.

    # type: ignore

    near the top of the file; this tells type checkers to ignore all annotations. (More fine-grained ways of disabling complaints from type checkers can be found in PEP 484.)

    Like linters, type checkers are optional, separate tools. Python interpreters by default should not issue any messages due to type checking and should not alter their behavior based on annotations.

    Users who don’t want to use type checkers are free to ignore them. However, it is expected that users of third party library packages may want to run type checkers over those packages. For this purpose PEP 484 recommends the use of stub files: .pyi files that are read by the type checker in preference of the corresponding .py files. Stub files can be distributed with a library, or separately (with the library author’s permission) through the typeshed repo [5].

    파일 상단 근처; 이는 유형 검사기가 모든 주석을 무시하도록 지시합니다. (유형 검사기의 불만 사항을 비활성화하는 보다 세밀한 방법은 PEP 484에서 찾을 수 있습니다.)

    린터와 마찬가지로 유형 검사기는 선택 사항이며 별도의 도구입니다. 기본적으로 Python 인터프리터는 유형 검사로 인해 메시지를 발행해서는 안 되며 주석을 기반으로 동작을 변경해서는 안 됩니다.

    유형 검사기를 사용하고 싶지 않은 사용자는 이를 무시해도 됩니다. 그러나 타사 라이브러리 패키지 사용자는 해당 패키지에 대해 유형 검사기를 실행할 수 있습니다. 이러한 목적으로 PEP 484는 스텁 파일(해당 .py 파일보다 유형 검사기가 읽는 .pyi 파일)을 사용할 것을 권장합니다. 스텁 파일은 라이브러리와 함께 배포하거나 형식화된 저장소[5]를 통해 별도로(라이브러리 작성자의 허가를 받아) 배포할 수 있습니다.

    Variable Annotations

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

    PEP 526에는 변수 주석이 도입되었습니다. 이에 대한 스타일 권장 사항은 위에 설명된 함수 주석의 권장 사항과 유사합니다.

    Annotations for module level variables, class and instance variables, and local variables should have a single space after the colon.

    There should be no space before the colon.

    If an assignment has a right hand side, then the equality sign should have exactly one space on both sides:

    모듈 수준 변수, 클래스 및 인스턴스 변수, 지역 변수에 대한 주석은 콜론 뒤에 단일 공백이 있어야 합니다.

    콜론 앞에는 공백이 없어야 합니다.

    할당에 오른쪽이 있는 경우 등호 기호 양쪽에 정확히 하나의 공백이 있어야 합니다.

    # Correct:
    code: int
    
    class Point:
        coords: Tuple[int, int]
        label: str = '<unknown>'
    # Wrong:
    code:int  # No space after colon
    code : int  # Space before colon
    
    class Test:
        result: int=0  # No spaces around equality sign

    Although the PEP 526 is accepted for Python 3.6, the variable annotation syntax is the preferred syntax for stub files on all versions of Python (see PEP 484 for details).

    Footnotes

    PEP 526은 Python 3.6에서 허용되지만 변수 주석 구문은 모든 Python 버전의 스텁 파일에 대해 선호되는 구문입니다(자세한 내용은 PEP 484 참조).

    [1]

    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.

    내어쓰기는 단락의 첫 줄을 제외하고 모든 줄을 들여쓰는 조판 스타일입니다. Python의 맥락에서 이 용어는 괄호로 묶인 명령문의 여는 괄호가 해당 줄의 공백이 아닌 마지막 문자이고, 후속 줄은 닫는 괄호까지 들여쓰기되는 스타일을 설명하는 데 사용됩니다.

    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.

    728x90

    댓글

Designed by Tistory.