Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags more
Archives
관리 메뉴

프랙티스만이 살길. 프랙티스만이 살길.

PEP 8 - Style Guide for Python Code 한국어 번역 본문

파이썬/정리노트

PEP 8 - Style Guide for Python Code 한국어 번역

gaussian-goodman

pep 8을 한번 읽어보려다가 곧 토익도 봐야하는디 영어 연습도 할 겸 반장난으로 번역을 한번해보기로 했다.

혹시나 이 글을 진지하게 참고하신다면 이 글에는 매끄럽지 못한 번역과 의역이 시도 때도 없이 많이 나오니 원문을 꼭 보시길 추천드립니다...༼ つ ◕_◕ ༽つ

 

PEP 8 – Style Guide for Python Code | peps.python.org

PEP 8 – Style Guide for Python Code Author: Guido van Rossum , Barry Warsaw , Nick Coghlan Status: Active Type: Process Created: 05-Jul-2001 Post-History: 05-Jul-2001, 01-Aug-2013 Table of Contents This document gives coding conventions for the Python co

peps.python.org


서론(Introduction)

이 문서는 배포된 메인 파이썬에서 표준 라이브러리를 포함한 파이썬 코드에게 코딩 규약을 제시한다.

This document gives coding conventions for the Python code comprising the standard library in the main Python distribution.

파이썬 내의 c코드 구현은 해당 pep를 참고하시오.

Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python.

이 문서와 PEP 257은  Guido’s original Python Style Guide essay를 각색되었고 Barry’s style guide를 추가적으로 참고하였다.

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)

Guido의 주요한 통찰력중 하나는 코드는 쓰여지는 것보다 읽어질때가 훨씬 많다는 것이다.

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.

PEP 20가 말했듯이 가독성은 중요하다.

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!

특히 이 PEP를 준수하기 위해 하위호환성(break backwards)을 깨지마라.

In particular: do not break backwards compatibility just to comply with this PEP!

이 스타일 가이드를 무시할 수 있는 경우들

Some other good reasons to ignore a particular guideline:

  1. 가이드 라인을 적용하는 것이 가독성을 떨어트릴때, 심지어  이PEP에게 익숙한 사람에게 마저도
    When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
  2. 이 규약을 무시하게되더라도, 주변의 코들들과 일관성을 유지하라(아마 역사적 이유들 때문일것이다). 그렇지만 누군가의 똥을 청소할 기회 일지도.
    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).
  3. 더 이상 편집하지 않을 코드가 이 가이드라인 이전에 작성된 경우.
    Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.
  4. 이 스타일가이드가 추천하는 기능이 지원되지 않는 오래된 버전의 파이썬과 코드가 호환되어야 하는 경우.
    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)

각 들여쓰기의 수준 마다 4개의 공백을 사용해라

Use 4 spaces per indentation level.

연속된 코드줄은 감싸진 요소들을 파이썬의 내제적인 줄 결합이나 hanging indent를 사용하여 수직적으로 맞춰야한다.

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

hanging indent를 사용할 때는 첫줄의 인자가 없어야하고 이어지는 줄과 분명히 구별되어야한다.

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:

# 올바른 코드:

# 구분 기호를 기준으로 사용해 구별.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# 4개의 공백을 더하여 나머지 부분과 구별(역: 기본 들여쓰기 4개, 구별을 위한 4개 사용해 총 8개의 공백)
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# 나머지 줄에도 4개의 공백을 이용해 들여쓰기를 한다.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)
# 잘못된 코드:

# 첫줄에 인자가 없어야한다.
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# 들여쓰기가 구분되지 않으니 추가적인 들여쓰기가 필요하다.
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

여러 줄로 이어지는 코드에서 4칸 공백 들여쓰기 규칙은 선택 사항이다.

# hanging indent에는 4칸 공백이외의 것이 사용 될 수도 있다.
foo = long_function_name(
  var_one, var_two,
  var_three, var_four)

if문의 조건분분이 여러줄로 작성되어야할만큼 길어진다면, if, 공백 여는 기호( 소괄호 : ( )로 작성하면 자동으로 4칸 공백 들여쓰기가 나머지에 적용된어 만들어진다는 것에 주목해보자.

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.

이것은 if문 안의 코드들과 시각적인 충돌을 일으킬 수 있다.

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.

이 PEP에서는 위의 문제를 어떻게 해결할지 명확히 제시하지 않는다

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 (this_is_one_thing and
    that_is_another_thing):
    do_something()

# 구문 하이라이터가 있는 에디터에서 코멘트를 추가해 구별을 돕는다
if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    do_something()

# 이어지는 줄에 들여쓰기는 추가한다.
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)

모든 줄의 최대 글자는 79로 제한한다.

Limit all lines to a maximum of 79 characters.

구조적인 제약들이 적은 긴 텍스트 블록(독 스트릭이나 코멘트)는 72글자로 제한한다.

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.

이 제한은 창 폭이 80으로 설정된 편집기에서 자동줄바꿈을 피하기 위해 사용된다. 편집기가 glyph marker를 마지막 열에 배치 할지라도

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.

이것에 예외적이고 원천적으로 동의하는 팀이 있다면 99글자까지 늘려도 늘리고, 코멘트와 독스트링은 72글자까지 늘려도 좋다.

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.

파이썬 표준 라이브러리는 보수적이라 79글자를 유지한다(독스트링과 코멘트는 72글자까지)

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.

with 구문에서는 3.10버전 전에는 내제된 줄 바꿈을 사용할 수 없었기 때문에 이런상황에서는 괜찮다.

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

 

( 앞에서 논의한 if문의에서의 여러 줄을 통해 좀 더 고민해 볼 수 있다.) 

(See the previous discussion on multiline if-statements for further thoughts on the indentation of such multiline with-statements.)

with assert 구문또한 다른 예제이다.

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:

# 잘못된 코드:
# 연산자가 피연자로부터 멀리 떨어져있다.
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는 그의 Computers and Typesetting series에서 관습적인 규칙을 설명한다. "비록 단락에 있는 공식은 이항과 관계 연산자 뒤에 줄바꿈하지만, 화면에 표시되는 공식은 연산자 전에 줄바꿈한다."

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:

# 올바른 코드:
# 연산자와 피연자를 연결하기 쉽다.
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

파이썬 코드에서 지역적으로 관습을 따르는 한 앞에서 줄을 바꾸든 뒤에서 줄을 바꾸든 괜찮다. 새로운 스타일인  Knuth의 스일을 보자.

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.

공백줄은 연관된 one-liner들 사이에는 생략될 수 있다.

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.

파이싼은 컨트롤 + L 폼 피드(form feed)을 공백으로 받아들인다.많은 툴들이 이것을 페이지 구분자로 사용하여, 파일을 관련된 구분의 페이지 구분자로써 사용 할 수 있다.

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)

주요 파이썬 배포 버전들은 UTF-8로 인코딩 되어있고, 다른 인코딩을 배포하지 않는다.

Code in the core Python distribution should always use UTF-8, and should not have an encoding declaration.

표준 라이브러리에서 비UTF-8 인코들은 실험 목적으로만 사용되어야한다.

In the standard library, non-UTF-8 encodings should be used only for test purposes.

비ASCII 문자들의 사용을 자제하며 사람과 장소를 위해서만 사용하라.

Use non-ASCII characters sparingly, preferably only to denote places and human names.

데이터에로써 비ASCII문자를 사용한다면, z̯̯͡a̧͎̺l̡͓̫g̹̲o̡̼̘ 과 같은 어지러운 유니코드 문자나 바이트 순서 표시는 피하라.

If using non-ASCII characters as data, avoid noisy Unicode characters like z̯̯͡a̧͎̺l̡͓̫g̹̲o̡̼̘ and byte order marks.

파이썬 표준 라이브러리의 모든 식별자는 ASCII 식별자를 반드시 하용해야하며, 가능한 영어단어를 사용해야한다.(많은 경우 영어가 아닌 약어와 기술 용어가 사용된다.

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: 
    # Wrong:
    import sys, os
    

    이것도 괜찮다.
    okay to say this though:
  • # 올바른 코드:
    import os
    import sys
  • # 올바른 코드:
    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.
    임포트는 다음의 순서를 따라 그룹화되어야 한다.
    Imports should be grouped in the following order:
    1. 표준 라이브러리 임포트.Standard library imports.
    2. 관련된 서드파티 임포트. Related third party imports.
    3. 지역적 어플리케이션/라이브러리임포트. Local application/library specific imports.
    임포트 그룹사이에 빈줄을 두어야한다.
    You should put a blank line between each group of imports.
  • 절대 경로 임포트가 권장된다. 보다 가독성이 좋으며 임포트 시스템이 잘못 구성되었을때(예시로, 패키지 내부의 디렉토리가 sys.path에서 끝날 때)도 더 좋은 결과를 가져온다.(적어도 더 나은 에러 메시지를 준다,)
    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 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:Standard library code should avoid complex package layouts and always use absolute imports.
  • from . import sibling
    from .sibling import example
    

     

  • 클래스를 포함한 모듈로부터 클래스를 임포트할때는 이렇게 작성하라.
    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
    
    너의 작성식이 지역적 변수와 충돌을 발생시킨다면, 명시적으로 작성하자: 그리고"myclass.MyClass"와 "foo.bar.yourclass.YourClass"처럼 작성하자
    If this spelling causes local name clashes, then spell them explicitly:and use “myclass.MyClass” and “foo.bar.yourclass.YourClass”.
  • import myclass
    import foo.bar.yourclass
    

     

  • 와일드카드 임포트들(from  import *)은 사용을 자제해야한다. 그들이 네임스페이스에 현재 있는 이름들을 불분명하게 만들어 독자와 자동화된 도구들에게 혼란을 야기한다.
    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.
    와일드 카드 임포트를 사용할 수 있는 방어적 상황이 있는데, 공개 API의 내부 안터페이스중 하나로 발행되는 경우이다.
    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).
    이름을 이런방식으로 적용할때. public and internal interfaces 가이드라인은 계속 적용된다.
    When republishing names this way, the guidelines below regarding public and internal interfaces still apply.

모듈 레벨 던더 이름들(Module Level Dunder Names)

모듈 레벨"던더들"(즉, 두 개의 선행 밑줄과 두 개의 후행 밑줄이 있는 이름)은 as __all__, __author__, __version__, 등이있다.

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.

파이썬의 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)

파이썬에서, 단일 따옴표 문자열과 이중 따옴표 문자열은 동일합니다. 본 PEP는 이것을 권장히 않는다.

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.

세 개 따옴표로 묶인 문자열의 경우 PEP 257의 docstring 규칙과 일치하도록 항상 큰따옴표 문자를 사용하자.

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:
    # 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 ,  
  • 한편 슬라이스에서 콜론은 이진 연산자처럼 작동하며 양쪽에 동일한 양의 공백이 있어야한다.(최후순위 연사자처럼 다뤄라)
    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:
    # 올바른 코드:
    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]
    # 잘못된 코드:
    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)

  •  
  • 공백을 아무 곳이나 뒤로 미는 것을 피하자. 일반적으로 보이지 않기 때문에 혼란스러울 수 있다. 예를 들어 백슬래시 다음에 공백이 나타나고 새 줄이 선 연속 마커로 계산되지 않는다. 일부 편집기는 보존하지 않고 많은 프로젝트(CPython 자체와 같은)에는 이를 거부하는 사전 커밋 후크가 있다.
    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.
  • 항상 이 이진 연산자를 하나의 공간으로 둘러싸라. 할당(=), 증강 할당(+=, -== 등), 비교(=, <, <, >, <=, >=, in, not, is, not), 불린(and, or, not).
    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:
    # 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:
    # Wrong:
    def munge(input: AnyStr=None): ...
    def munge(input: AnyStr, limit = 1000): ...
    
  • # Correct:
    def munge(sep: AnyStr = None): ...
    def munge(input: AnyStr, sep: AnyStr = None, 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:
# 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()

 

 

추가예정...

 

'파이썬 > 정리노트' 카테고리의 다른 글

파이썬 파일경로. (역슬래쉬와 슬래쉬)  (0) 2023.07.05