5 dự án trăn

Trang web này được hỗ trợ rộng rãi bởi DataCamp. DataCamp cung cấp Hướng dẫn Python tương tác trực tuyến cho Khoa học dữ liệu. Join 575,000 other learners and get started learning Python for data science today

Welcome to the LearnPython. org interactive Python tutorial

Whether you are an experienced programmer or not, this website is intended for everyone who wishes to learn the Python programming language

You are welcome to join our group on Facebook for questions, discussions and updates

Sau khi bạn hoàn thành các hướng dẫn, bạn có thể được chứng nhận tại LearnX và thêm chứng nhận của bạn vào hồ sơ LinkedIn của bạn

Python là ngôn ngữ động chính được sử dụng tại Google. Hướng dẫn về phong cách này là danh sách những điều nên làm và không nên làm đối với các chương trình Python

Để giúp bạn định dạng mã chính xác, chúng tôi đã tạo tệp cài đặt cho Vim. Đối với Emacs, cài đặt mặc định sẽ ổn

Many teams use the yapf auto-formatter to avoid arguing over formatting

2 Python Language Rules

2. 1 Lint

Run

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
18 over your code using this pylintrc

2. 1. 1 Definition

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
18 is a tool for finding bugs and style problems in Python source code. It finds problems that are typically caught by a compiler for less dynamic languages like C and C++. Because of the dynamic nature of Python, some warnings may be incorrect; however, spurious warnings should be fairly infrequent

2. 1. 2 Pros

Catches easy-to-miss errors like typos, using-vars-before-assignment, etc

2. 1. 3 Cons

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
18 isn’t perfect. To take advantage of it, sometimes we’ll need to write around it, suppress its warnings or fix it

2. 1. 4 Decision

Make sure you run

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
18 on your code

Suppress warnings if they are inappropriate so that other issues are not hidden. To suppress warnings, you can set a line-level comment

dict = 'something awful'  # Bad Idea.. pylint: disable=redefined-builtin

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
18 warnings are each identified by symbolic name (
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
23) Google-specific warnings start with
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
24

If the reason for the suppression is not clear from the symbolic name, add an explanation

Suppressing in this way has the advantage that we can easily search for suppressions and revisit them

You can get a list of

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
18 warnings by doing

To get more information on a particular message, use

Prefer

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
26 to the deprecated older form
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
27

Unused argument warnings can be suppressed by deleting the variables at the beginning of the function. Always include a comment explaining why you are deleting it. “Unused. ” is sufficient. For example

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam

Other common forms of suppressing this warning include using ‘

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
28’ as the identifier for the unused argument or prefixing the argument name with ‘
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
29’, or assigning them to ‘
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
28’. These forms are allowed but no longer encouraged. These break callers that pass arguments by name and do not enforce that the arguments are actually unused

2. 2 Imports

Use

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
31 statements for packages and modules only, not for individual classes or functions

2. 2. 1 Definition

Reusability mechanism for sharing code from one module to another

2. 2. 2 Pros

The namespace management convention is simple. The source of each identifier is indicated in a consistent way;

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
32 says that object
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
33 is defined in module
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
34

2. 2. 3 Cons

Module names can still collide. Một số tên mô-đun dài bất tiện

2. 2. 4 Decision

  • Use
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    35 for importing packages and modules
  • Use
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    36 where
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    34 is the package prefix and
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    38 is the module name with no prefix
  • Use
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    39 if two modules named
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    38 are to be imported, if
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    38 conflicts with a top-level name defined in the current module, or if
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    38 is an inconveniently long name
  • Use
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    43 only when
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    44 is a standard abbreviation (e. g. ,
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    45 for
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    46)

For example the module

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
47 may be imported as follows

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)

Do not use relative names in imports. Even if the module is in the same package, use the full package name. This helps prevent unintentionally importing a package twice

2. 2. 4. 1 Exemptions

Exemptions from this rule

  • Symbols from the following modules are used to support static analysis and type checking
  • Redirects from the

2. 3 Packages

Import each module using the full pathname location of the module

2. 3. 1 Pros

Avoids conflicts in module names or incorrect imports due to the module search path not being what the author expected. Makes it easier to find modules

2. 3. 2 Cons

Makes it harder to deploy code because you have to replicate the package hierarchy. Not really a problem with modern deployment mechanisms

2. 3. 3 Decision

All new code should import each module by its full package name

Imports should be as follows

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)

(assume this file lives in

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
48 where
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
49 also exists)

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie

The directory the main binary is located in should not be assumed to be in

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
50 despite that happening in some environments. This being the case, code should assume that
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
51 refers to a third party or top level package named
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
52, not a local
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
49

2. 4 Exceptions

Exceptions are allowed but must be used carefully

2. 4. 1 Definition

Exceptions are a means of breaking out of normal control flow to handle errors or other exceptional conditions

2. 4. 2 Pros

The control flow of normal operation code is not cluttered by error-handling code. It also allows the control flow to skip multiple frames when a certain condition occurs, e. g. , returning from N nested functions in one step instead of having to plumb error codes through

2. 4. 3 Cons

May cause the control flow to be confusing. Easy to miss error cases when making library calls

2. 4. 4 Decision

Exceptions must follow certain conditions

  • Make use of built-in exception classes when it makes sense. For example, raise a

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    54 to indicate a programming mistake like a violated precondition (such as if you were passed a negative number but required a positive one). Do not use
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    55 statements for validating argument values of a public API.
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    55 is used to ensure internal correctness, not to enforce correct usage nor to indicate that some unexpected event occurred. Nếu một ngoại lệ được mong muốn trong các trường hợp sau, hãy sử dụng câu lệnh nâng cao. Ví dụ

    Yes:
      def connect_to_next_port(self, minimum: int) -> int:
        """Connects to the next available port.
    
        Args:
          minimum: A port value greater or equal to 1024.
    
        Returns:
          The new minimum port.
    
        Raises:
          ConnectionError: If no available port is found.
        """
        if minimum < 1024:
          # Note that this raising of ValueError is not mentioned in the doc
          # string's "Raises:" section because it is not appropriate to
          # guarantee this specific behavioral reaction to API misuse.
          raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
        port = self._find_next_open_port(minimum)
        if port is None:
          raise ConnectionError(
              f'Could not connect to service on port {minimum} or higher.')
        assert port >= minimum, (
            f'Unexpected port {port} when minimum was {minimum}.')
        return port
    

    No:
      def connect_to_next_port(self, minimum: int) -> int:
        """Connects to the next available port.
    
        Args:
          minimum: A port value greater or equal to 1024.
    
        Returns:
          The new minimum port.
        """
        assert minimum >= 1024, 'Minimum port must be at least 1024.'
        port = self._find_next_open_port(minimum)
        assert port is not None
        return port
    

  • Thư viện hoặc gói có thể xác định ngoại lệ của riêng họ. Khi làm như vậy, họ phải kế thừa từ một lớp ngoại lệ hiện có. Tên ngoại lệ phải kết thúc bằng

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    57 và không nên lặp lại (
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    58)

  • Không bao giờ sử dụng câu lệnh bắt tất cả

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    59 hoặc bắt
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    60 hoặc
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    61, trừ khi bạn

    • tăng lại ngoại lệ, hoặc
    • tạo một điểm cô lập trong chương trình nơi các ngoại lệ không được lan truyền mà thay vào đó được ghi lại và loại bỏ, chẳng hạn như bảo vệ một luồng khỏi sự cố bằng cách bảo vệ khối ngoài cùng của nó

    Python rất khoan dung về vấn đề này và

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    59 sẽ thực sự nắm bắt mọi thứ kể cả tên sai chính tả, sys. các lệnh gọi exit(), Ctrl+C ngắt, lỗi nhỏ nhất và tất cả các loại ngoại lệ khác mà bạn đơn giản là không muốn nắm bắt

  • Giảm thiểu số lượng mã trong một khối

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    63/
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    64. Phần thân của
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    63 càng lớn thì càng có nhiều khả năng một ngoại lệ sẽ được đưa ra bởi một dòng mã mà bạn không mong đợi sẽ đưa ra một ngoại lệ. Trong những trường hợp đó, khối
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    63/
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    64 ẩn một lỗi thực sự

  • Sử dụng mệnh đề

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    68 để thực thi mã cho dù có hay không một ngoại lệ được đưa ra trong khối
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    63. Điều này thường hữu ích cho việc dọn dẹp, tôi. e. , đóng một tập tin

2. 5 trạng thái toàn cầu có thể thay đổi

Tránh trạng thái toàn cầu có thể thay đổi

2. 5. 1 Định nghĩa

Module level values or class attributes that can get mutated during program execution

2. 5. 2 Pros

Occasionally useful

2. 5. 3 Cons

  • Breaks encapsulation. Such design can make it hard to achieve valid objectives. For example, if global state is used to manage a database connection, then connecting to two different databases at the same time (such as for computing differences during a migration) becomes difficult. Similar problems easily arise with global registries

  • Has the potential to change module behavior during the import, because assignments to global variables are done when the module is first imported

2. 5. 4 Decision

Tránh trạng thái toàn cầu có thể thay đổi

In those rare cases where using global state is warranted, mutable global entities should be declared at the module level or as a class attribute and made internal by prepending an

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
28 to the name. If necessary, external access to mutable global state must be done through public functions or class methods. See below. Please explain the design reasons why mutable global state is being used in a comment or a doc linked to from a comment

Module-level constants are permitted and encouraged. For example.

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
71 for an internal use constant or
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
72 for a public API constant. Constants must be named using all caps with underscores. See below

2. 6 Nested/Local/Inner Classes and Functions

Nested local functions or classes are fine when used to close over a local variable. Inner classes are fine

2. 6. 1 Definition

A class can be defined inside of a method, function, or class. A function can be defined inside a method or function. Nested functions have read-only access to variables defined in enclosing scopes

2. 6. 2 Pros

Allows definition of utility classes and functions that are only used inside of a very limited scope. Rất ADT-y. Thường được sử dụng để thực hiện trang trí

2. 6. 3 nhược điểm

Các hàm và lớp lồng nhau không thể được kiểm tra trực tiếp. Việc lồng nhau có thể làm cho chức năng bên ngoài dài hơn và khó đọc hơn

2. 6. 4 Quyết định

Họ ổn với một số lưu ý. Tránh các hàm hoặc lớp lồng nhau trừ khi đóng trên một giá trị cục bộ khác với

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
73 hoặc
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
74. Không lồng chức năng chỉ để ẩn nó khỏi người dùng mô-đun. Thay vào đó, hãy đặt tiền tố tên của nó bằng _ ở cấp độ mô-đun để nó vẫn có thể được truy cập bằng các thử nghiệm

2. 7 cách hiểu và biểu thức trình tạo

Được rồi để sử dụng cho các trường hợp đơn giản

2. 7. 1 Định nghĩa

Khả năng hiểu List, Dict và Set cũng như các biểu thức trình tạo cung cấp một cách ngắn gọn và hiệu quả để tạo các loại bộ chứa và bộ lặp mà không cần sử dụng các vòng lặp truyền thống,

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
75,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
76 hoặc
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
77

2. 7. 2 Ưu điểm

Việc hiểu đơn giản có thể rõ ràng và đơn giản hơn các kỹ thuật tạo chính tả, danh sách hoặc tập hợp khác. Biểu thức trình tạo có thể rất hiệu quả, vì chúng hoàn toàn tránh được việc tạo danh sách

2. 7. 3 nhược điểm

Có thể khó đọc các biểu thức trình tạo hoặc hiểu phức tạp

2. 7. 4 Quyết định

Được rồi để sử dụng cho các trường hợp đơn giản. Mỗi phần phải vừa trên một dòng. biểu thức ánh xạ, mệnh đề

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
78, biểu thức bộ lọc. Nhiều mệnh đề
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
78 hoặc biểu thức bộ lọc không được phép. Thay vào đó, hãy sử dụng các vòng lặp khi mọi thứ trở nên phức tạp hơn

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
      for y in range(5):
          if x * y > 10:
              result.append((x, y))

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

  squares_generator = (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}

  eat(jelly_bean for jelly_bean in jelly_beans
      if jelly_bean.color == 'black')

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)

2. 8 Iterator và Operator mặc định

Sử dụng các trình lặp và toán tử mặc định cho các loại hỗ trợ chúng, như danh sách, từ điển và tệp

2. 8. 1 Định nghĩa

Các loại vùng chứa, như từ điển và danh sách, xác định các trình vòng lặp mặc định và toán tử kiểm tra tư cách thành viên (“in” và “not in”)

2. 8. 2 Ưu điểm

Các trình vòng lặp và toán tử mặc định rất đơn giản và hiệu quả. Chúng thể hiện thao tác trực tiếp mà không cần gọi thêm phương thức. Một hàm sử dụng các toán tử mặc định là chung chung. Nó có thể được sử dụng với bất kỳ loại nào hỗ trợ hoạt động

2. 8. 3 nhược điểm

Bạn không thể biết loại đối tượng bằng cách đọc tên phương thức (trừ khi biến có chú thích loại). Đây cũng là một lợi thế

2. 8. 4 Quyết định

Sử dụng các trình lặp và toán tử mặc định cho các loại hỗ trợ chúng, như danh sách, từ điển và tệp. Các loại tích hợp cũng xác định các phương thức lặp. Ưu tiên các phương thức này hơn các phương thức trả về danh sách, ngoại trừ việc bạn không nên thay đổi vùng chứa trong khi lặp lại nó

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
0

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
1

2. 9 máy phát điện

Sử dụng máy phát điện khi cần thiết

2. 9. 1 Định nghĩa

Hàm tạo trả về một trình vòng lặp mang lại một giá trị mỗi khi nó thực thi câu lệnh năng suất. Sau khi nó mang lại một giá trị, trạng thái thời gian chạy của hàm tạo bị tạm dừng cho đến khi cần giá trị tiếp theo

2. 9. 2 Ưu điểm

Mã đơn giản hơn, vì trạng thái của các biến cục bộ và luồng điều khiển được giữ nguyên cho mỗi cuộc gọi. Trình tạo sử dụng ít bộ nhớ hơn so với hàm tạo toàn bộ danh sách giá trị cùng một lúc

2. 9. 3 nhược điểm

Các biến cục bộ trong trình tạo sẽ không được thu gom rác cho đến khi trình tạo bị tiêu thụ đến mức cạn kiệt hoặc chính nó đã được thu gom rác

2. 9. 4 Quyết định

Khỏe. Sử dụng “Năng suất. ” thay vì “Trả về. ” trong chuỗi tài liệu cho các hàm tạo

Nếu trình tạo quản lý một tài nguyên đắt tiền, hãy đảm bảo buộc dọn dẹp

Một cách hay để dọn dẹp là bọc trình tạo bằng trình quản lý ngữ cảnh PEP-0533

2. 10 Hàm Lambda

Được rồi cho một lớp lót. Thích các biểu thức trình tạo hơn

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
75 hoặc
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
76 với một
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
77

2. 10. 1 Định nghĩa

Lambdas định nghĩa các hàm ẩn danh trong một biểu thức, trái ngược với một câu lệnh

2. 10. 2 Ưu điểm

Thuận lợi

2. 10. 3 nhược điểm

Khó đọc và gỡ lỗi hơn các chức năng cục bộ. Việc thiếu tên có nghĩa là dấu vết ngăn xếp khó hiểu hơn. Tính biểu cảm bị hạn chế vì chức năng chỉ có thể chứa một biểu thức

2. 10. 4 Quyết định

Được rồi để sử dụng chúng cho một lớp lót. Nếu mã bên trong hàm lambda dài hơn 60-80 ký tự, thì có lẽ tốt hơn nên xác định mã đó là mã thông thường

Đối với các hoạt động phổ biến như phép nhân, hãy sử dụng các hàm từ mô-đun

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
83 thay vì các hàm lambda. Ví dụ: thích
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
84 hơn là
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
85

2. 11 Biểu thức điều kiện

Được rồi cho các trường hợp đơn giản

2. 11. 1 Định nghĩa

Biểu thức điều kiện (đôi khi được gọi là “toán tử bậc ba”) là cơ chế cung cấp cú pháp ngắn hơn cho câu lệnh if. Ví dụ.

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
86

2. 11. 2 Ưu điểm

Ngắn gọn và thuận tiện hơn câu lệnh if

2. 11. 3 nhược điểm

Có thể khó đọc hơn câu lệnh if. Điều kiện có thể khó xác định nếu biểu thức dài

2. 11. 4 Quyết định

Được rồi để sử dụng cho các trường hợp đơn giản. Mỗi phần phải vừa trên một dòng. biểu thức đúng, biểu thức if, biểu thức khác. Sử dụng câu lệnh if hoàn chỉnh khi mọi thứ trở nên phức tạp hơn

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
2

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
3

2. 12 giá trị đối số mặc định

Được rồi trong hầu hết các trường hợp

2. 12. 1 Định nghĩa

Bạn có thể chỉ định giá trị cho các biến ở cuối danh sách tham số của hàm, chẳng hạn như. g. ,

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
87. Nếu
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
88 được gọi chỉ với một đối số, thì
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
89 được đặt thành 0. Nếu nó được gọi với hai đối số, thì
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
89 có giá trị của đối số thứ hai

2. 12. 2 Ưu điểm

Thường thì bạn có một hàm sử dụng nhiều giá trị mặc định, nhưng trong một số trường hợp hiếm hoi, bạn muốn ghi đè lên các giá trị mặc định. Các giá trị đối số mặc định cung cấp một cách dễ dàng để thực hiện việc này mà không cần phải xác định nhiều hàm cho các trường hợp ngoại lệ hiếm gặp. Vì Python không hỗ trợ các phương thức/hàm quá tải, nên các đối số mặc định là một cách dễ dàng để “làm giả” hành vi quá tải

2. 12. 3 nhược điểm

Các đối số mặc định được đánh giá một lần tại thời điểm tải mô-đun. Điều này có thể gây ra sự cố nếu đối số là đối tượng có thể thay đổi, chẳng hạn như danh sách hoặc từ điển. Nếu chức năng sửa đổi đối tượng (e. g. , bằng cách thêm một mục vào danh sách), giá trị mặc định được sửa đổi

2. 12. 4 Quyết định

Được rồi để sử dụng với cảnh báo sau

Không sử dụng các đối tượng có thể thay đổi làm giá trị mặc định trong định nghĩa hàm hoặc phương thức

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
4

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
5

2. 13 thuộc tính

Các thuộc tính có thể được sử dụng để kiểm soát việc nhận hoặc thiết lập các thuộc tính yêu cầu tính toán hoặc logic thông thường. Việc triển khai thuộc tính phải phù hợp với kỳ vọng chung của quyền truy cập thuộc tính thông thường. rằng chúng rẻ, đơn giản và không gây ngạc nhiên

2. 13. 1 Định nghĩa

Một cách để gói các cuộc gọi phương thức để nhận và đặt thuộc tính làm quyền truy cập thuộc tính tiêu chuẩn

2. 13. 2 Ưu điểm

  • Cho phép API gán và truy cập thuộc tính thay vì gọi phương thức
  • Có thể được sử dụng để tạo thuộc tính chỉ đọc
  • Cho phép tính toán lười biếng
  • Cung cấp một cách để duy trì giao diện chung của một lớp khi các phần bên trong phát triển độc lập với người dùng lớp

2. 13. 3 nhược điểm

  • Có thể ẩn các tác dụng phụ giống như quá tải toán tử
  • Có thể gây nhầm lẫn cho các lớp con

2. 13. 4 Quyết định

Các thuộc tính được cho phép, nhưng, giống như quá tải toán tử, chỉ nên được sử dụng khi cần thiết và phù hợp với mong đợi của truy cập thuộc tính điển hình;

Ví dụ: không được phép sử dụng thuộc tính để vừa lấy vừa đặt thuộc tính nội bộ. không có tính toán xảy ra, vì vậy thuộc tính là không cần thiết (). Trong khi đó, việc sử dụng một thuộc tính để kiểm soát quyền truy cập thuộc tính hoặc để tính toán một giá trị có nguồn gốc tầm thường được cho phép. logic rất đơn giản và không có gì đáng ngạc nhiên

Các thuộc tính nên được tạo bằng

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
91. Thực hiện thủ công một bộ mô tả thuộc tính được coi là một

Kế thừa với các thuộc tính có thể không rõ ràng. Không sử dụng các thuộc tính để thực hiện tính toán mà một lớp con có thể muốn ghi đè và mở rộng

2. 14 Đánh giá Đúng/Sai

Sử dụng sai "ngầm" nếu có thể

2. 14. 1 Định nghĩa

Python đánh giá các giá trị nhất định là

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
92 khi ở trong ngữ cảnh boolean. Một “quy tắc ngón tay cái” nhanh là tất cả các giá trị “trống rỗng” đều được coi là sai, vì vậy, ________93 tất cả đều được đánh giá là sai trong ngữ cảnh boolean

2. 14. 2 Ưu điểm

Các điều kiện sử dụng booleans Python dễ đọc hơn và ít bị lỗi hơn. Trong hầu hết các trường hợp, chúng cũng nhanh hơn

2. 14. 3 nhược điểm

Có thể trông lạ đối với các nhà phát triển C/C++

2. 14. 4 Quyết định

Sử dụng sai “ngầm” nếu có thể, e. g. ,

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
94 thay vì
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
95. Có một vài cảnh báo mà bạn nên ghi nhớ mặc dù

  • Luôn sử dụng

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    96 (hoặc
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    97) để kiểm tra giá trị
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98. e. g. , khi kiểm tra xem một biến hoặc đối số mặc định là
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98 có được đặt thành một số giá trị khác không. Giá trị khác có thể là một giá trị sai trong ngữ cảnh boolean

  • Không bao giờ so sánh một biến boolean với

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    92 bằng cách sử dụng
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    01. Sử dụng
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    02 để thay thế. Nếu bạn cần phân biệt
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    92 với
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98 thì hãy xâu chuỗi các biểu thức, chẳng hạn như
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    05

  • Đối với các chuỗi (chuỗi, danh sách, bộ dữ liệu), hãy sử dụng thực tế là các chuỗi trống là sai, do đó,

    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    06 và
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    07 được ưu tiên hơn so với
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    08 và
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    09 tương ứng

  • Khi xử lý các số nguyên, sai ngầm định có thể gây ra nhiều rủi ro hơn là lợi ích (i. e. , vô tình xử lý

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98 thành 0). Bạn có thể so sánh một giá trị được biết là một số nguyên (và không phải là kết quả của
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    11) với số nguyên 0

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    6

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    7

  • Lưu ý rằng

    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    12 (tôi. e. ,
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    13 dưới dạng chuỗi) đánh giá là true

  • Lưu ý rằng các mảng Numpy có thể đưa ra một ngoại lệ trong ngữ cảnh boolean ngầm định. Ưu tiên thuộc tính

    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    14 khi kiểm tra tính không của một
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    15 (e. g.
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    16)

2. 16 Phạm vi từ vựng

Được rồi để sử dụng

2. 16. 1 Định nghĩa

Một hàm Python lồng nhau có thể tham chiếu đến các biến được xác định trong các hàm kèm theo, nhưng không thể gán cho chúng. Các liên kết biến được giải quyết bằng cách sử dụng phạm vi từ vựng, nghĩa là dựa trên văn bản chương trình tĩnh. Bất kỳ sự gán nào cho một tên trong một khối sẽ khiến Python coi tất cả các tham chiếu đến tên đó là một biến cục bộ, ngay cả khi việc sử dụng có trước sự gán. Nếu một khai báo toàn cầu xảy ra, tên được coi là một biến toàn cầu

Một ví dụ về việc sử dụng tính năng này là

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
8

2. 16. 2 Ưu điểm

Thường dẫn đến mã rõ ràng hơn, thanh lịch hơn. Đặc biệt an ủi các lập trình viên Lisp và Scheme (và Haskell, ML và…) có kinh nghiệm

2. 16. 3 nhược điểm

Có thể dẫn đến các lỗi khó hiểu. Chẳng hạn như ví dụ này dựa trên PEP-0227

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
9

Vì vậy,

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
17 sẽ in ra
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
18, không phải
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
19

2. 16. 4 Quyết định

Được rồi để sử dụng

2. 17 Trình trang trí chức năng và phương thức

Sử dụng decorators một cách thận trọng khi có một lợi thế rõ ràng. Tránh

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
20 và hạn chế sử dụng
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
21

2. 17. 1 Định nghĩa

(Một. k. một “ký hiệu

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
22”). Một trình trang trí phổ biến là
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
91, được sử dụng để chuyển đổi các phương thức thông thường thành các thuộc tính được tính toán động. Tuy nhiên, cú pháp của trình trang trí cũng cho phép các trình trang trí do người dùng định nghĩa. Cụ thể, đối với một số chức năng
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
24, điều này

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
0

tương đương với

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
1

2. 17. 2 Ưu điểm

Chỉ định một cách trang nhã một số chuyển đổi trên một phương thức;

2. 17. 3 nhược điểm

Trình trang trí có thể thực hiện các thao tác tùy ý trên đối số của hàm hoặc trả về giá trị, dẫn đến hành vi ngầm đáng ngạc nhiên. Ngoài ra, các trình trang trí thực thi tại thời điểm xác định đối tượng. Đối với các đối tượng cấp mô-đun (lớp, chức năng mô-đun,…) điều này xảy ra tại thời điểm nhập. Lỗi trong mã trang trí hầu như không thể phục hồi từ

2. 17. 4 Quyết định

Sử dụng decorators một cách thận trọng khi có một lợi thế rõ ràng. Người trang trí phải tuân theo các nguyên tắc nhập và đặt tên giống như các chức năng. Trình trang trí pydoc phải nêu rõ rằng chức năng này là một trình trang trí. Viết bài kiểm tra đơn vị cho người trang trí

Tránh các phụ thuộc bên ngoài trong chính trình trang trí (e. g. không dựa vào tệp, ổ cắm, kết nối cơ sở dữ liệu, v.v. ), vì chúng có thể không khả dụng khi trình trang trí chạy (tại thời điểm nhập, có thể từ

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
25 hoặc các công cụ khác). Một trình trang trí được gọi với các tham số hợp lệ phải (càng nhiều càng tốt) được đảm bảo thành công trong mọi trường hợp

Trình trang trí là trường hợp đặc biệt của “mã cấp cao nhất” - xem để thảo luận thêm

Không bao giờ sử dụng

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
20 trừ khi bị buộc phải tích hợp với API được xác định trong thư viện hiện có. Thay vào đó hãy viết một hàm cấp mô-đun

Chỉ sử dụng

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
21 khi viết một hàm tạo được đặt tên hoặc một quy trình dành riêng cho lớp để sửa đổi trạng thái chung cần thiết, chẳng hạn như bộ đệm trên toàn quy trình

2. 18 luồng

Không dựa vào tính nguyên tử của các loại tích hợp

Mặc dù các kiểu dữ liệu tích hợp sẵn của Python, chẳng hạn như từ điển, dường như có các hoạt động nguyên tử, nhưng có một số trường hợp chúng không phải là nguyên tử (e. g. nếu

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
28 hoặc
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
29 được triển khai dưới dạng phương thức Python) và không nên dựa vào tính nguyên tử của chúng. Bạn cũng không nên dựa vào phép gán biến nguyên tử (vì điều này lại phụ thuộc vào từ điển)

Sử dụng kiểu dữ liệu

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
30 của mô-đun Hàng đợi làm cách ưu tiên để truyền dữ liệu giữa các luồng. Otherwise, use the threading module and its locking primitives. Ưu tiên các biến điều kiện và
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
31 thay vì sử dụng các khóa cấp thấp hơn

2. 19 Tính năng nguồn

Tránh các tính năng này

2. 19. 1 Định nghĩa

Python là một ngôn ngữ cực kỳ linh hoạt và cung cấp cho bạn nhiều tính năng ưa thích như siêu dữ liệu tùy chỉnh, quyền truy cập vào mã byte, biên dịch nhanh, kế thừa động, sửa chữa đối tượng, hack nhập, phản ánh (e. g. một số cách sử dụng của

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
32), sửa đổi bên trong hệ thống, phương pháp
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
33 thực hiện dọn dẹp tùy chỉnh, v.v.

2. 19. 2 Ưu điểm

Đây là những tính năng ngôn ngữ mạnh mẽ. Họ có thể làm cho mã của bạn gọn hơn

2. 19. 3 nhược điểm

Rất hấp dẫn khi sử dụng những tính năng “hay ho” này khi chúng không thực sự cần thiết. Khó đọc, hiểu và gỡ lỗi mã đang sử dụng các tính năng bất thường bên dưới. Thoạt đầu có vẻ không phải như vậy (đối với tác giả gốc), nhưng khi xem lại mã, nó có xu hướng khó hơn mã dài hơn nhưng đơn giản

2. 19. 4 Quyết định

Tránh các tính năng này trong mã của bạn

Các mô-đun và lớp thư viện tiêu chuẩn sử dụng nội bộ các tính năng này đều được phép sử dụng (ví dụ:

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
34,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
35 và
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
36)

2. 20 con trăn hiện đại. từ __future__ nhập khẩu

Các thay đổi ngữ nghĩa của phiên bản ngôn ngữ mới có thể được kiểm soát sau quá trình nhập đặc biệt trong tương lai để kích hoạt chúng trên cơ sở từng tệp trong thời gian chạy trước đó

2. 20. 1 Định nghĩa

Có thể bật một số tính năng hiện đại hơn thông qua câu lệnh

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
37 cho phép sử dụng sớm các tính năng từ các phiên bản Python dự kiến ​​trong tương lai

2. 20. 2 Ưu điểm

Điều này đã được chứng minh là giúp nâng cấp phiên bản thời gian chạy mượt mà hơn vì các thay đổi có thể được thực hiện trên cơ sở từng tệp trong khi khai báo tính tương thích và ngăn chặn hồi quy trong các tệp đó. Mã hiện đại dễ bảo trì hơn vì ít có khả năng tích lũy nợ kỹ thuật sẽ gây ra sự cố trong quá trình nâng cấp thời gian chạy trong tương lai

2. 20. 3 nhược điểm

Mã như vậy có thể không hoạt động trên các phiên bản thông dịch viên rất cũ trước khi đưa ra câu lệnh tương lai cần thiết. Nhu cầu này phổ biến hơn trong các dự án hỗ trợ rất nhiều môi trường

2. 20. 4 Quyết định

từ __future__ nhập khẩu

Việc sử dụng các câu lệnh

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
37 được khuyến khích. Nó cho phép một tệp nguồn nhất định bắt đầu sử dụng các tính năng cú pháp Python hiện đại hơn ngày nay. Sau khi bạn không còn cần chạy trên phiên bản mà các tính năng bị ẩn đằng sau lần nhập
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
39, vui lòng xóa các dòng đó

Trong mã có thể thực thi trên các phiên bản cũ như 3. 5 thay vì >= 3. 7, nhập khẩu

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
2

Để biết thêm thông tin, hãy đọc tài liệu định nghĩa câu lệnh tương lai của Python

Vui lòng không xóa các mục nhập này cho đến khi bạn tin rằng mã này chỉ được sử dụng trong một môi trường đủ hiện đại. Ngay cả khi bạn hiện không sử dụng tính năng mà một tính năng nhập cụ thể trong tương lai cho phép trong mã của bạn hôm nay, thì việc giữ nguyên tính năng này trong tệp sẽ ngăn việc vô tình sửa đổi mã sau này tùy thuộc vào hành vi cũ hơn

Sử dụng các câu lệnh nhập khẩu

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
40 khác khi bạn thấy phù hợp

2. 21 Loại mã chú thích

Bạn có thể chú thích mã Python bằng gợi ý loại theo PEP-484 và kiểm tra loại mã khi xây dựng bằng công cụ kiểm tra loại như pytype

Loại chú thích có thể trong nguồn hoặc trong một. Bất cứ khi nào có thể, chú thích nên ở trong nguồn. Sử dụng tệp pyi cho bên thứ ba hoặc mô-đun mở rộng

2. 21. 1 Định nghĩa

Chú thích kiểu (hoặc “gợi ý kiểu”) dành cho các đối số của hàm hoặc phương thức và giá trị trả về

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
3

Bạn cũng có thể khai báo loại biến bằng cú pháp PEP-526 tương tự

2. 21. 2 Ưu điểm

Loại chú thích cải thiện khả năng đọc và bảo trì mã của bạn. Trình kiểm tra loại sẽ chuyển đổi nhiều lỗi thời gian chạy thành lỗi thời gian xây dựng và giảm khả năng sử dụng của bạn

2. 21. 3 nhược điểm

Bạn sẽ phải cập nhật các khai báo kiểu. Bạn có thể thấy lỗi loại mà bạn nghĩ là mã hợp lệ. Việc sử dụng bộ kiểm tra loại có thể làm giảm khả năng sử dụng của bạn

2. 21. 4 Quyết định

Bạn được khuyến khích bật phân tích kiểu Python khi cập nhật mã. Khi thêm hoặc sửa đổi API công khai, hãy bao gồm các chú thích loại và cho phép kiểm tra qua pytype trong hệ thống xây dựng. Vì phân tích tĩnh còn tương đối mới đối với Python, chúng tôi thừa nhận rằng các tác dụng phụ không mong muốn (chẳng hạn như các loại được suy luận sai) có thể ngăn một số dự án áp dụng. Trong những trường hợp đó, các tác giả được khuyến khích thêm nhận xét bằng TODO hoặc liên kết đến lỗi mô tả (các) sự cố hiện đang ngăn cản việc áp dụng chú thích loại trong tệp BUILD hoặc trong chính mã nếu phù hợp

3 quy tắc kiểu Python

3. 1 dấu chấm phẩy

Do not terminate your lines with semicolons, and do not use semicolons to put two statements on the same line

3. 2 Chiều dài dòng

Độ dài dòng tối đa là 80 ký tự

Ngoại lệ rõ ràng đối với giới hạn 80 ký tự

  • Báo cáo nhập khẩu dài
  • URL, tên đường dẫn hoặc cờ dài trong nhận xét
  • Các hằng số cấp mô-đun chuỗi dài không chứa khoảng trắng sẽ gây bất tiện khi chia thành các dòng như URL hoặc tên đường dẫn
    • Pylint vô hiệu hóa bình luận. (e. g.
      from sound.effects import echo
      ...
      echo.EchoFilter(input, output, delay=0.7, atten=4)
      
      41)

Không sử dụng tiếp tục dòng gạch chéo ngược ngoại trừ câu lệnh

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
42 yêu cầu ba trình quản lý ngữ cảnh trở lên

Tận dụng Python. Nếu cần, bạn có thể thêm một cặp dấu ngoặc đơn xung quanh một biểu thức

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
4

Khi một chuỗi ký tự không vừa trên một dòng, hãy sử dụng dấu ngoặc đơn để nối dòng ẩn

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
5

Trong các nhận xét, hãy đặt các URL dài trên dòng riêng của chúng nếu cần

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
6

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
7

Có thể sử dụng tiếp tục dấu gạch chéo ngược khi xác định câu lệnh

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
42 với ba trình quản lý ngữ cảnh trở lên. Đối với hai trình quản lý bối cảnh, hãy sử dụng câu lệnh
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
42 lồng nhau

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
8

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
9

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
0

Lưu ý về sự thụt đầu dòng của các phần tử trong các ví dụ tiếp tục dòng ở trên;

Trong tất cả các trường hợp khác khi một dòng vượt quá 80 ký tự và trình định dạng tự động yapf không giúp đưa dòng xuống dưới giới hạn, thì dòng đó được phép vượt quá mức tối đa này. Các tác giả được khuyến khích ngắt dòng theo cách thủ công theo ghi chú ở trên khi thấy hợp lý

3. 3 dấu ngoặc đơn

Sử dụng dấu ngoặc đơn một cách tiết kiệm

Nó là tốt, mặc dù không bắt buộc, để sử dụng dấu ngoặc đơn xung quanh bộ dữ liệu. Không sử dụng chúng trong các câu lệnh trả về hoặc câu lệnh có điều kiện trừ khi sử dụng dấu ngoặc đơn để tiếp tục dòng ngụ ý hoặc để chỉ ra một bộ

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
1

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
2

3. 4 Thụt đầu dòng

Thụt lề các khối mã của bạn với 4 dấu cách

Không bao giờ sử dụng các tab. Việc tiếp tục dòng ngụ ý phải căn chỉnh các phần tử được bao theo chiều dọc (xem) hoặc sử dụng thụt lề 4 dấu cách treo. Dấu ngoặc đóng (tròn, vuông hoặc cong) có thể được đặt ở cuối biểu thức hoặc trên các dòng riêng biệt, nhưng sau đó phải được thụt vào giống như dòng có dấu ngoặc mở tương ứng

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
3

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
4

3. 4. 1 Dấu phẩy ở cuối dãy các mục?

Dấu phẩy ở cuối trong chuỗi các mục chỉ được khuyến nghị khi mã thông báo vùng chứa đóng

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
45,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
46 hoặc
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
47 không xuất hiện trên cùng một dòng với phần tử cuối cùng. Sự hiện diện của dấu phẩy ở cuối cũng được sử dụng như một gợi ý cho trình định dạng tự động mã YAPF của mã Python của chúng tôi để hướng dẫn nó tự động định dạng vùng chứa các mục thành một mục trên mỗi dòng khi có mặt
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
48 sau phần tử cuối cùng

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
5

3. 5 dòng trống

Hai dòng trống giữa các định nghĩa cấp cao nhất, có thể là định nghĩa hàm hoặc lớp. Một dòng trống giữa các định nghĩa phương thức và giữa chuỗi tài liệu của

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
49 và phương thức đầu tiên. Không có dòng trống nào sau dòng
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
50. Sử dụng các dòng trống đơn khi bạn đánh giá phù hợp trong các hàm hoặc phương thức

Các dòng trống không cần phải được neo vào định nghĩa. Ví dụ: các nhận xét liên quan ngay trước các định nghĩa hàm, lớp và phương thức có thể có ý nghĩa. Cân nhắc xem nhận xét của bạn có thể hữu ích hơn như một phần của chuỗi tài liệu không

3. 6 Khoảng trắng

Thực hiện theo các quy tắc đánh máy tiêu chuẩn để sử dụng khoảng trắng xung quanh dấu chấm câu

Không có khoảng trắng bên trong dấu ngoặc đơn, dấu ngoặc hoặc dấu ngoặc nhọn

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
6

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
7

Không có khoảng trắng trước dấu phẩy, dấu chấm phẩy hoặc dấu hai chấm. Sử dụng khoảng trắng sau dấu phẩy, dấu chấm phẩy hoặc dấu hai chấm, ngoại trừ ở cuối dòng

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
8

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
9

Không có khoảng trắng trước dấu ngoặc đơn/ngoặc mở bắt đầu danh sách đối số, lập chỉ mục hoặc cắt

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
0

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
1

Không có khoảng trắng ở cuối

Bao quanh các toán tử nhị phân với một khoảng trắng ở hai bên để gán (

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
51), so sánh (
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
52) và Booleans (
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
53). Sử dụng khả năng phán đoán tốt hơn của bạn để chèn khoảng trắng xung quanh các toán tử số học (
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
54,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
55,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
56,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
57,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
58,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
59,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
60,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
22)

Không bao giờ sử dụng khoảng trắng xung quanh

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
51 khi chuyển đối số từ khóa hoặc xác định giá trị tham số mặc định, với một ngoại lệ. , hãy sử dụng khoảng trắng xung quanh
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
51 cho giá trị tham số mặc định

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
2

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
3

Không sử dụng khoảng trắng để sắp xếp theo chiều dọc các mã thông báo trên các dòng liên tiếp, vì nó sẽ trở thành gánh nặng bảo trì (áp dụng cho

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
64,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
65,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
51, v.v. )

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
4

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
5

3. 7 dòng Shebang

Hầu hết các tệp

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
67 không cần bắt đầu bằng dòng
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
68. Bắt đầu tệp chính của chương trình với
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
69 (để hỗ trợ virtualenv) hoặc
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
70 mỗi PEP-394

Dòng này được nhân sử dụng để tìm trình thông dịch Python, nhưng bị Python bỏ qua khi nhập mô-đun. Nó chỉ cần thiết trên một tệp dự định được thực thi trực tiếp

Đảm bảo sử dụng đúng kiểu cho mô-đun, hàm, chuỗi tài liệu phương thức và nhận xét nội tuyến

3. 8. 1 tài liệu

Python sử dụng docstrings để viết mã tài liệu. Chuỗi tài liệu là một chuỗi là câu lệnh đầu tiên trong gói, mô-đun, lớp hoặc hàm. Các chuỗi này có thể được trích xuất tự động thông qua thành viên

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
71 của đối tượng và được sử dụng bởi
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
25. (Hãy thử chạy
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
25 trên mô-đun của bạn để xem nó trông như thế nào. ) Luôn sử dụng định dạng ba trích dẫn kép
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
74 cho các chuỗi tài liệu (theo PEP 257). Chuỗi tài liệu phải được tổ chức dưới dạng một dòng tóm tắt (một dòng vật lý không quá 80 ký tự) được kết thúc bằng dấu chấm, dấu chấm hỏi hoặc dấu chấm than. Khi viết thêm (khuyến khích), dòng này phải được theo sau bởi một dòng trống, tiếp theo là phần còn lại của chuỗi tài liệu bắt đầu ở cùng vị trí con trỏ với trích dẫn đầu tiên của dòng đầu tiên. Có nhiều hướng dẫn định dạng hơn cho các tài liệu bên dưới

3. 8. 2 mô-đun

Mỗi tệp phải chứa giấy phép soạn sẵn. Chọn bản soạn sẵn thích hợp cho giấy phép được dự án sử dụng (ví dụ: Apache 2. 0, BSD, LGPL, GPL)

Các tệp phải bắt đầu bằng một chuỗi tài liệu mô tả nội dung và cách sử dụng mô-đun

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
6

3. 8. 2. 1 mô-đun thử nghiệm

Không bắt buộc phải có chuỗi tài liệu cấp mô-đun cho các tệp thử nghiệm. Chúng chỉ nên được đưa vào khi có thông tin bổ sung có thể được cung cấp

Các ví dụ bao gồm một số chi tiết cụ thể về cách chạy thử nghiệm, giải thích về mẫu thiết lập bất thường, sự phụ thuộc vào môi trường bên ngoài, v.v.

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
7

Không nên sử dụng các chuỗi tài liệu không cung cấp bất kỳ thông tin mới nào

3. 8. 3 Hàm và Phương thức

Trong phần này, "hàm" có nghĩa là một phương thức, chức năng, trình tạo hoặc thuộc tính

Một chuỗi tài liệu là bắt buộc đối với mọi chức năng có một hoặc nhiều thuộc tính sau

  • là một phần của API công khai
  • kích thước không tầm thường
  • logic không rõ ràng

Một chuỗi tài liệu phải cung cấp đủ thông tin để viết lệnh gọi đến hàm mà không cần đọc mã của hàm. Chuỗi tài liệu phải mô tả cú pháp gọi của hàm và ngữ nghĩa của nó, nhưng nói chung không phải là chi tiết triển khai của nó, trừ khi những chi tiết đó có liên quan đến cách sử dụng hàm. Ví dụ: một hàm thay đổi một trong các đối số của nó dưới dạng tác dụng phụ cần lưu ý rằng trong chuỗi tài liệu của nó. Mặt khác, các chi tiết tinh tế nhưng quan trọng về việc triển khai chức năng không liên quan đến người gọi sẽ được thể hiện dưới dạng nhận xét bên cạnh mã tốt hơn là trong chuỗi tài liệu của chức năng

Chuỗi tài liệu có thể là kiểu mô tả (

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
75) hoặc kiểu mệnh lệnh (
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
76), nhưng kiểu này phải nhất quán trong một tệp. Chuỗi tài liệu cho bộ mô tả dữ liệu
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
91 nên sử dụng cùng kiểu với chuỗi tài liệu cho một thuộc tính hoặc (
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
78, thay vì
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
79)

Một phương thức ghi đè một phương thức từ lớp cơ sở có thể có một chuỗi tài liệu đơn giản gửi trình đọc đến chuỗi tài liệu của phương thức được ghi đè, chẳng hạn như

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
80. Cơ sở lý luận là không cần phải lặp lại ở nhiều nơi tài liệu đã có trong chuỗi tài liệu của phương thức cơ sở. Tuy nhiên, nếu hành vi của phương thức ghi đè về cơ bản khác với phương thức bị ghi đè hoặc cần cung cấp thông tin chi tiết (e. g. , ghi lại các tác dụng phụ bổ sung), một chuỗi tài liệu có ít nhất những điểm khác biệt đó là bắt buộc đối với phương thức ghi đè

Một số khía cạnh của một chức năng nên được ghi lại trong các phần đặc biệt, được liệt kê bên dưới. Mỗi phần bắt đầu bằng một dòng tiêu đề, kết thúc bằng dấu hai chấm. Tất cả các phần không phải là tiêu đề nên duy trì thụt lề treo hai hoặc bốn khoảng trắng (nhất quán trong một tệp). Các phần này có thể được bỏ qua trong trường hợp tên và chữ ký của hàm đủ thông tin để có thể mô tả chính xác bằng cách sử dụng chuỗi tài liệu một dòng

Liệt kê từng tham số theo tên. Mô tả phải theo sau tên và được phân tách bằng dấu hai chấm, sau đó là khoảng trắng hoặc xuống dòng. Nếu mô tả quá dài để vừa với một dòng 80 ký tự, hãy sử dụng thụt lề treo nhiều hơn 2 hoặc 4 khoảng trắng so với tên tham số (nhất quán với phần còn lại của chuỗi tài liệu trong tệp). Mô tả phải bao gồm (các) loại bắt buộc nếu mã không chứa chú thích loại tương ứng. Nếu một hàm chấp nhận
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
81 (danh sách đối số có độ dài thay đổi) và/hoặc
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
82 (đối số từ khóa tùy ý), thì chúng phải được liệt kê là
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
81 và
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
82. Mô tả loại và ngữ nghĩa của giá trị trả về. Nếu hàm chỉ trả về Không thì không cần phần này. Nó cũng có thể được bỏ qua nếu chuỗi tài liệu bắt đầu bằng Returns hoặc Yields (e. g.
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
85) and the opening sentence is sufficient to describe the return value. Do not imitate ‘NumPy style’ (example), which frequently documents a tuple return value as if it were multiple return values with individual names (never mentioning the tuple). Instead, describe such a return value as. “Returns. A tuple (mat_a, mat_b), where mat_a is …, and …”. The auxiliary names in the docstring need not necessarily correspond to any internal names used in the function body (as those are not part of the API). List all exceptions that are relevant to the interface followed by a description. Use a similar exception name + colon + space or newline and hanging indent style as described in Args. You should not document exceptions that get raised if the API specified in the docstring is violated (because this would paradoxically make behavior under violation of the API part of the API)

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
8

Similarly, this variation on

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
86 with a line break is also allowed

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
9

3. 8. 4 Classes

Classes should have a docstring below the class definition describing the class. If your class has public attributes, they should be documented here in an

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
87 section and follow the same formatting as a section

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie
0

All class docstrings should start with a one-line summary that describes what the class instance represents. This implies that subclasses of

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
60 should also describe what the exception represents, and not the context in which it might occur. The class docstring should not repeat unnecessary information, such as that the class is a class

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie
1

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie
2

3. 8. 5 Block and Inline Comments

The final place to have comments is in tricky parts of the code. If you’re going to have to explain it at the next code review, you should comment it now. Complicated operations get a few lines of comments before the operations commence. Non-obvious ones get comments at the end of the line

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie
3

To improve legibility, these comments should start at least 2 spaces away from the code with the comment character

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
65, followed by at least one space before the text of the comment itself

On the other hand, never describe the code. Assume the person reading the code knows Python (though not what you’re trying to do) better than you do

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie
4

3. 8. 6 Punctuation, Spelling, and Grammar

Pay attention to punctuation, spelling, and grammar; it is easier to read well-written comments than badly written ones

Comments should be as readable as narrative text, with proper capitalization and punctuation. In many cases, complete sentences are more readable than sentence fragments. Shorter comments, such as comments at the end of a line of code, can sometimes be less formal, but you should be consistent with your style

Although it can be frustrating to have a code reviewer point out that you are using a comma when you should be using a semicolon, it is very important that source code maintain a high level of clarity and readability. Proper punctuation, spelling, and grammar help with that goal

3. 10 Strings

Use an , the

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
59 operator, or the
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
92 method for formatting strings, even when the parameters are all strings. Use your best judgment to decide between string formatting options. A single join with
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
54 is okay but do not format with
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
54

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie
5

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie
6

Avoid using the

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
54 and
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
96 operators to accumulate a string within a loop. In some conditions, accumulating a string with addition can lead to quadratic rather than linear running time. Although common accumulations of this sort may be optimized on CPython, that is an implementation detail. The conditions under which an optimization applies are not easy to predict and may change. Instead, add each substring to a list and
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
97 the list after the loop terminates, or write each substring to an
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
98 buffer. These techniques consistently have amortized-linear run time complexity

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie
7

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie
8

Be consistent with your choice of string quote character within a file. Pick

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
99 or
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
00 and stick with it. It is okay to use the other quote character on a string to avoid the need to backslash-escape quote characters within the string

No:
  # Unclear what module the author wanted and what will be imported.  The actual
  # import behavior depends on external factors controlling sys.path.
  # Which possible jodie module did the author intend to import?
  import jodie
9

Yes:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.

    Raises:
      ConnectionError: If no available port is found.
    """
    if minimum < 1024:
      # Note that this raising of ValueError is not mentioned in the doc
      # string's "Raises:" section because it is not appropriate to
      # guarantee this specific behavioral reaction to API misuse.
      raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
    port = self._find_next_open_port(minimum)
    if port is None:
      raise ConnectionError(
          f'Could not connect to service on port {minimum} or higher.')
    assert port >= minimum, (
        f'Unexpected port {port} when minimum was {minimum}.')
    return port
0

Prefer

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
74 for multi-line strings rather than
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
02. Projects may choose to use
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
02 for all non-docstring multi-line strings if and only if they also use
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
99 for regular strings. Docstrings must use
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
74 regardless

Multi-line strings do not flow with the indentation of the rest of the program. If you need to avoid embedding extra space in the string, use either concatenated single-line strings or a multi-line string with to remove the initial space on each line

Yes:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.

    Raises:
      ConnectionError: If no available port is found.
    """
    if minimum < 1024:
      # Note that this raising of ValueError is not mentioned in the doc
      # string's "Raises:" section because it is not appropriate to
      # guarantee this specific behavioral reaction to API misuse.
      raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
    port = self._find_next_open_port(minimum)
    if port is None:
      raise ConnectionError(
          f'Could not connect to service on port {minimum} or higher.')
    assert port >= minimum, (
        f'Unexpected port {port} when minimum was {minimum}.')
    return port
1

Yes:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.

    Raises:
      ConnectionError: If no available port is found.
    """
    if minimum < 1024:
      # Note that this raising of ValueError is not mentioned in the doc
      # string's "Raises:" section because it is not appropriate to
      # guarantee this specific behavioral reaction to API misuse.
      raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
    port = self._find_next_open_port(minimum)
    if port is None:
      raise ConnectionError(
          f'Could not connect to service on port {minimum} or higher.')
    assert port >= minimum, (
        f'Unexpected port {port} when minimum was {minimum}.')
    return port
2

Yes:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.

    Raises:
      ConnectionError: If no available port is found.
    """
    if minimum < 1024:
      # Note that this raising of ValueError is not mentioned in the doc
      # string's "Raises:" section because it is not appropriate to
      # guarantee this specific behavioral reaction to API misuse.
      raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
    port = self._find_next_open_port(minimum)
    if port is None:
      raise ConnectionError(
          f'Could not connect to service on port {minimum} or higher.')
    assert port >= minimum, (
        f'Unexpected port {port} when minimum was {minimum}.')
    return port
3

Yes:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.

    Raises:
      ConnectionError: If no available port is found.
    """
    if minimum < 1024:
      # Note that this raising of ValueError is not mentioned in the doc
      # string's "Raises:" section because it is not appropriate to
      # guarantee this specific behavioral reaction to API misuse.
      raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
    port = self._find_next_open_port(minimum)
    if port is None:
      raise ConnectionError(
          f'Could not connect to service on port {minimum} or higher.')
    assert port >= minimum, (
        f'Unexpected port {port} when minimum was {minimum}.')
    return port
4

Yes:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.

    Raises:
      ConnectionError: If no available port is found.
    """
    if minimum < 1024:
      # Note that this raising of ValueError is not mentioned in the doc
      # string's "Raises:" section because it is not appropriate to
      # guarantee this specific behavioral reaction to API misuse.
      raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
    port = self._find_next_open_port(minimum)
    if port is None:
      raise ConnectionError(
          f'Could not connect to service on port {minimum} or higher.')
    assert port >= minimum, (
        f'Unexpected port {port} when minimum was {minimum}.')
    return port
5

3. 10. 1 Logging

For logging functions that expect a pattern-string (with %-placeholders) as their first argument. Always call them with a string literal (not an f-string. ) as their first argument with pattern-parameters as subsequent arguments. Some logging implementations collect the unexpanded pattern-string as a queryable field. It also prevents spending time rendering a message that no logger is configured to output

Yes:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.

    Raises:
      ConnectionError: If no available port is found.
    """
    if minimum < 1024:
      # Note that this raising of ValueError is not mentioned in the doc
      # string's "Raises:" section because it is not appropriate to
      # guarantee this specific behavioral reaction to API misuse.
      raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
    port = self._find_next_open_port(minimum)
    if port is None:
      raise ConnectionError(
          f'Could not connect to service on port {minimum} or higher.')
    assert port >= minimum, (
        f'Unexpected port {port} when minimum was {minimum}.')
    return port
6

Yes:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.

    Raises:
      ConnectionError: If no available port is found.
    """
    if minimum < 1024:
      # Note that this raising of ValueError is not mentioned in the doc
      # string's "Raises:" section because it is not appropriate to
      # guarantee this specific behavioral reaction to API misuse.
      raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
    port = self._find_next_open_port(minimum)
    if port is None:
      raise ConnectionError(
          f'Could not connect to service on port {minimum} or higher.')
    assert port >= minimum, (
        f'Unexpected port {port} when minimum was {minimum}.')
    return port
7

Yes:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.

    Raises:
      ConnectionError: If no available port is found.
    """
    if minimum < 1024:
      # Note that this raising of ValueError is not mentioned in the doc
      # string's "Raises:" section because it is not appropriate to
      # guarantee this specific behavioral reaction to API misuse.
      raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
    port = self._find_next_open_port(minimum)
    if port is None:
      raise ConnectionError(
          f'Could not connect to service on port {minimum} or higher.')
    assert port >= minimum, (
        f'Unexpected port {port} when minimum was {minimum}.')
    return port
8

3. 10. 2 Error Messages

Error messages (such as. message strings on exceptions like

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
54, or messages shown to the user) should follow three guidelines

  1. The message needs to precisely match the actual error condition

  2. Interpolated pieces need to always be clearly identifiable as such

  3. They should allow simple automated processing (e. g. grepping)

Yes:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.

    Raises:
      ConnectionError: If no available port is found.
    """
    if minimum < 1024:
      # Note that this raising of ValueError is not mentioned in the doc
      # string's "Raises:" section because it is not appropriate to
      # guarantee this specific behavioral reaction to API misuse.
      raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
    port = self._find_next_open_port(minimum)
    if port is None:
      raise ConnectionError(
          f'Could not connect to service on port {minimum} or higher.')
    assert port >= minimum, (
        f'Unexpected port {port} when minimum was {minimum}.')
    return port
9

No:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.
    """
    assert minimum >= 1024, 'Minimum port must be at least 1024.'
    port = self._find_next_open_port(minimum)
    assert port is not None
    return port
0

3. 11 Files, Sockets, and similar Stateful Resources

Explicitly close files and sockets when done with them. This rule naturally extends to closeable resources that internally use sockets, such as database connections, and also other resources that need to be closed down in a similar fashion. To name only a few examples, this also includes mmap mappings, h5py File objects, and matplotlib. pyplot figure windows

Leaving files, sockets or other such stateful objects open unnecessarily has many downsides

  • They may consume limited system resources, such as file descriptors. Code that deals with many such objects may exhaust those resources unnecessarily if they’re not returned to the system promptly after use
  • Holding files open may prevent other actions such as moving or deleting them, or unmounting a filesystem
  • Files and sockets that are shared throughout a program may inadvertently be read from or written to after logically being closed. If they are actually closed, attempts to read or write from them will raise exceptions, making the problem known sooner

Furthermore, while files and sockets (and some similarly behaving resources) are automatically closed when the object is destructed, coupling the lifetime of the object to the state of the resource is poor practice

  • There are no guarantees as to when the runtime will actually invoke the
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    33 method. Different Python implementations use different memory management techniques, such as delayed garbage collection, which may increase the object’s lifetime arbitrarily and indefinitely
  • Unexpected references to the file, e. g. in globals or exception tracebacks, may keep it around longer than intended

Relying on finalizers to do automatic cleanup that has observable side effects has been rediscovered over and over again to lead to major problems, across many decades and multiple languages (see e. g. this article for Java)

The preferred way to manage files and similar resources is using the

No:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.
    """
    assert minimum >= 1024, 'Minimum port must be at least 1024.'
    port = self._find_next_open_port(minimum)
    assert port is not None
    return port
1

For file-like objects that do not support the

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
42 statement, use
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
11

No:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.
    """
    assert minimum >= 1024, 'Minimum port must be at least 1024.'
    port = self._find_next_open_port(minimum)
    assert port is not None
    return port
2

In rare cases where context-based resource management is infeasible, code documentation must explain clearly how resource lifetime is managed

Use

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 comments for code that is temporary, a short-term solution, or good-enough but not perfect

A

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 comment begins with the word
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 in all caps, and a parenthesized context identifier. Ideally a bug reference, sometimes a username. A bug reference like
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
15 is preferable, because bugs are tracked and have follow-up comments, whereas individuals move around and may lose context over time. The
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 is followed by an explanation of what there is to do

The purpose is to have a consistent

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 format that can be searched to find out how to get more details. A
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 is not a commitment that the person referenced will fix the problem. Thus when you create a
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 with a username, it is almost always your own username that is given

No:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.
    """
    assert minimum >= 1024, 'Minimum port must be at least 1024.'
    port = self._find_next_open_port(minimum)
    assert port is not None
    return port
3

If your

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 is of the form “At a future date do something” make sure that you either include a very specific date (“Fix by November 2009”) or a very specific event (“Remove this code when all clients can handle XML responses. ”) that future code maintainers will comprehend

3. 13 Imports formatting

Imports should be on separate lines; there are

E. g

No:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.
    """
    assert minimum >= 1024, 'Minimum port must be at least 1024.'
    port = self._find_next_open_port(minimum)
    assert port is not None
    return port
4

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 from most generic to least generic

  1. Python future import statements. For example

    No:
      def connect_to_next_port(self, minimum: int) -> int:
        """Connects to the next available port.
    
        Args:
          minimum: A port value greater or equal to 1024.
    
        Returns:
          The new minimum port.
        """
        assert minimum >= 1024, 'Minimum port must be at least 1024.'
        port = self._find_next_open_port(minimum)
        assert port is not None
        return port
    
    5

    See for more information about those

  2. Python standard library imports. For example

  3. third-party module or package imports. For example

  4. Code repository sub-package imports. For example

    No:
      def connect_to_next_port(self, minimum: int) -> int:
        """Connects to the next available port.
    
        Args:
          minimum: A port value greater or equal to 1024.
    
        Returns:
          The new minimum port.
        """
        assert minimum >= 1024, 'Minimum port must be at least 1024.'
        port = self._find_next_open_port(minimum)
        assert port is not None
        return port
    
    6

  5. Deprecated. application-specific imports that are part of the same top level sub-package as this file. For example

    No:
      def connect_to_next_port(self, minimum: int) -> int:
        """Connects to the next available port.
    
        Args:
          minimum: A port value greater or equal to 1024.
    
        Returns:
          The new minimum port.
        """
        assert minimum >= 1024, 'Minimum port must be at least 1024.'
        port = self._find_next_open_port(minimum)
        assert port is not None
        return port
    
    7

    You may find older Google Python Style code doing this, but it is no longer required. New code is encouraged not to bother with this. Simply treat application-specific sub-package imports the same as other sub-package imports

Within each grouping, imports should be sorted lexicographically, ignoring case, according to each module’s full package path (the

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
23 in
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
24). Code may optionally place a blank line between import sections

No:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.
    """
    assert minimum >= 1024, 'Minimum port must be at least 1024.'
    port = self._find_next_open_port(minimum)
    assert port is not None
    return port
8

3. 14 Tuyên bố

Generally only one statement per line

However, you may put the result of a test on the same line as the test only if the entire statement fits on one line. In particular, you can never do so with

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
63/
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
64 since the
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
63 and
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
64 can’t both fit on the same line, and you can only do so with an
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
29 if there is no
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
30

No:
  def connect_to_next_port(self, minimum: int) -> int:
    """Connects to the next available port.

    Args:
      minimum: A port value greater or equal to 1024.

    Returns:
      The new minimum port.
    """
    assert minimum >= 1024, 'Minimum port must be at least 1024.'
    port = self._find_next_open_port(minimum)
    assert port is not None
    return port
9

3. 15 Getters và Setters

Các hàm getter và setter (còn được gọi là bộ truy cập và bộ biến đổi) nên được sử dụng khi chúng cung cấp vai trò hoặc hành vi có ý nghĩa để nhận hoặc đặt giá trị của biến

Đặc biệt, chúng nên được sử dụng khi nhận hoặc thiết lập biến phức tạp hoặc chi phí đáng kể, hiện tại hoặc trong tương lai hợp lý

If, for example, a pair of getters/setters simply read and write an internal attribute, the internal attribute should be made public instead. Để so sánh, nếu việc đặt một biến có nghĩa là một số trạng thái bị vô hiệu hóa hoặc được xây dựng lại, thì đó phải là một hàm setter. Lời gọi hàm gợi ý rằng một hoạt động có khả năng không tầm thường đang xảy ra. Ngoài ra, có thể là một tùy chọn khi cần logic đơn giản hoặc tái cấu trúc để không còn cần getters và setters nữa

Getters and setters should follow the guidelines, such as

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
31 and
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
32

If the past behavior allowed access through a property, do not bind the new getter/setter functions to the property. Any code still attempting to access the variable by the old method should break visibly so they are made aware of the change in complexity

3. 16 Naming

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
33,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
34,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
35,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
36,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
37,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
38,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
39,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
40,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
41,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
42,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
43,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
44,
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
45

Function names, variable names, and filenames should be descriptive; avoid abbreviation. In particular, do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word

Always use a

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
67 filename extension. Never use dashes

3. 16. 1 Names to Avoid

  • single character names, except for specifically allowed cases

    • counters or iterators (e. g.
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      47,
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      48,
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      49,
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      50, et al. )
    • Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      51 as an exception identifier in
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      52 statements
    • Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      53 as a file handle in
      from sound.effects import echo
      ...
      echo.EchoFilter(input, output, delay=0.7, atten=4)
      
      42 statements
    • private with no constraints (e. g.
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      56,
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      57,
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      58)

    Please be mindful not to abuse single-character naming. Generally speaking, descriptiveness should be proportional to the name’s scope of visibility. For example,

    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    47 might be a fine name for 5-line code block but within multiple nested scopes, it is likely too vague

  • dashes (

    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    55) in any package/module name

  • Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    61 names (reserved by Python)

  • offensive terms

  • names that needlessly include the type of the variable (for example.

    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    62)

3. 16. 2 Naming Conventions

  • “Internal” means internal to a module, or protected or private within a class

  • Prepending a single underscore (

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    28) has some support for protecting module variables and functions (linters will flag protected member access)

  • Prepending a double underscore (

    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    64 aka “dunder”) to an instance variable or method effectively makes the variable or method private to its class (using name mangling); we discourage its use as it impacts readability and testability, and isn’t really private. Prefer a single underscore

  • Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module

  • Use CapWords for class names, but lower_with_under. py for module names. Although there are some old modules named CapWords. py, this is now discouraged because it’s confusing when the module happens to be named after a class. (“wait – did I write

    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    65 or
    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    66?”)

  • Underscores may appear in unittest method names starting with

    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    67 to separate logical components of the name, even if those components use CapWords. One possible pattern is
    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    68; for example
    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    69 is okay. There is no One Correct Way to name test methods

3. 16. 3 File Naming

Python filenames must have a

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
67 extension and must not contain dashes (
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
55). This allows them to be imported and unittested. If you want an executable to be accessible without the extension, use a symbolic link or a simple bash wrapper containing
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
72

3. 16. 4 Guidelines derived from Guido’s Recommendations

TypePublicInternalPackages
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
73Modules
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
73
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
75Classes
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
76
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
77Exceptions
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
76Functions
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
79
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
80Global/Class Constants
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
81
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
82Global/Class Variables
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
73
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
75Instance Variables
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
73
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
75 (protected)Method Names
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
79
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
80 (protected)Function/Method Parameters
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
73Local Variables
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
73

3. 16. 5 Mathematical Notation

For mathematically heavy code, short variable names that would otherwise violate the style guide are preferred when they match established notation in a reference paper or algorithm. When doing so, reference the source of all naming conventions in a comment or docstring or, if the source is not accessible, clearly document the naming conventions. Prefer PEP8-compliant

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
91 for public APIs, which are much more likely to be encountered out of context

3. 17 Main

In Python,

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
25 as well as unit tests require modules to be importable. If a file is meant to be used as an executable, its main functionality should be in a
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
93 function, and your code should always check
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
94 before executing your main program, so that it is not executed when the module is imported

When using absl, use

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
95

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
      for y in range(5):
          if x * y > 10:
              result.append((x, y))

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

  squares_generator = (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}

  eat(jelly_bean for jelly_bean in jelly_beans
      if jelly_bean.color == 'black')
0

Otherwise, use

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
      for y in range(5):
          if x * y > 10:
              result.append((x, y))

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

  squares_generator = (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}

  eat(jelly_bean for jelly_bean in jelly_beans
      if jelly_bean.color == 'black')
1

All code at the top level will be executed when the module is imported. Be careful not to call functions, create objects, or perform other operations that should not be executed when the file is being

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
25ed

3. 18 Function length

Prefer small and focused functions

We recognize that long functions are sometimes appropriate, so no hard limit is placed on function length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program

Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code

You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code. if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces

3. 19 Type Annotations

3. 19. 1 General Rules

  • Familiarize yourself with PEP-484

  • In methods, only annotate

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    73, or
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    74 if it is necessary for proper type information. e. g. ,

    Yes:
      result = [mapping_expr for value in iterable if filter_expr]
    
      result = [{'key': value} for value in iterable
                if a_long_filter_expression(value)]
    
      result = [complicated_transform(x)
                for x in iterable if predicate(x)]
    
      descriptive_name = [
          transform({'key': key, 'value': value}, color='black')
          for key, value in generate_iterable(some_input)
          if complicated_condition_is_met(key, value)
      ]
    
      result = []
      for x in range(10):
          for y in range(5):
              if x * y > 10:
                  result.append((x, y))
    
      return {x: complicated_transform(x)
              for x in long_generator_function(parameter)
              if x is not None}
    
      squares_generator = (x**2 for x in range(10))
    
      unique_names = {user.name for user in users if user is not None}
    
      eat(jelly_bean for jelly_bean in jelly_beans
          if jelly_bean.color == 'black')
    
    2

  • Similarly, don’t feel compelled to annotate the return value of

    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    99 (where
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98 is the only valid option)

  • If any other variable or a returned type should not be expressed, use

    Yes:
      # Reference flags in code with just the module name (common).
      from absl import flags
      from doctor.who import jodie
    
      _FOO = flags.DEFINE_string(...)
    
    01

  • You are not required to annotate all the functions in a module

    • At least annotate your public APIs
    • Use judgment to get to a good balance between safety and clarity on the one hand, and flexibility on the other
    • Annotate code that is prone to type-related errors (previous bugs or complexity)
    • Annotate code that is hard to understand
    • Annotate code as it becomes stable from a types perspective. In many cases, you can annotate all the functions in mature code without losing too much flexibility

3. 19. 2 Line Breaking

Try to follow the existing rules

After annotating, many function signatures will become “one parameter per line”. To ensure the return type is also given its own line, a comma can be placed after the last parameter

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
      for y in range(5):
          if x * y > 10:
              result.append((x, y))

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

  squares_generator = (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}

  eat(jelly_bean for jelly_bean in jelly_beans
      if jelly_bean.color == 'black')
3

Always prefer breaking between variables, and not, for example, between variable names and type annotations. However, if everything fits on the same line, go for it

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
      for y in range(5):
          if x * y > 10:
              result.append((x, y))

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

  squares_generator = (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}

  eat(jelly_bean for jelly_bean in jelly_beans
      if jelly_bean.color == 'black')
4

If the combination of the function name, the last parameter, and the return type is too long, indent by 4 in a new line. When using line breaks, prefer putting each parameter and the return type on their own lines and aligning the closing parenthesis with the

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
50

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
      for y in range(5):
          if x * y > 10:
              result.append((x, y))

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

  squares_generator = (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}

  eat(jelly_bean for jelly_bean in jelly_beans
      if jelly_bean.color == 'black')
5

Optionally, the return type may be put on the same line as the last parameter

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
      for y in range(5):
          if x * y > 10:
              result.append((x, y))

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

  squares_generator = (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}

  eat(jelly_bean for jelly_bean in jelly_beans
      if jelly_bean.color == 'black')
6

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
18 allows you to move the closing parenthesis to a new line and align with the opening one, but this is less readable

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
      for y in range(5):
          if x * y > 10:
              result.append((x, y))

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

  squares_generator = (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}

  eat(jelly_bean for jelly_bean in jelly_beans
      if jelly_bean.color == 'black')
7

As in the examples above, prefer not to break types. However, sometimes they are too long to be on a single line (try to keep sub-types unbroken)

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
      for y in range(5):
          if x * y > 10:
              result.append((x, y))

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

  squares_generator = (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}

  eat(jelly_bean for jelly_bean in jelly_beans
      if jelly_bean.color == 'black')
8

If a single name and type is too long, consider using an for the type. The last resort is to break after the colon and indent by 4

Yes:
  result = [mapping_expr for value in iterable if filter_expr]

  result = [{'key': value} for value in iterable
            if a_long_filter_expression(value)]

  result = [complicated_transform(x)
            for x in iterable if predicate(x)]

  descriptive_name = [
      transform({'key': key, 'value': value}, color='black')
      for key, value in generate_iterable(some_input)
      if complicated_condition_is_met(key, value)
  ]

  result = []
  for x in range(10):
      for y in range(5):
          if x * y > 10:
              result.append((x, y))

  return {x: complicated_transform(x)
          for x in long_generator_function(parameter)
          if x is not None}

  squares_generator = (x**2 for x in range(10))

  unique_names = {user.name for user in users if user is not None}

  eat(jelly_bean for jelly_bean in jelly_beans
      if jelly_bean.color == 'black')
9

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)
0

3. 19. 3 Forward Declarations

If you need to use a class name (from the same module) that is not yet defined – for example, if you need the class name inside the declaration of that class, or if you use a class that is defined later in the code – either use

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
04 or use a string for the class name

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)
1

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)
2

3. 19. 4 Default Values

As per , use spaces around the

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
51 only for arguments that have both a type annotation and a default value

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)
3

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)
4

3. 19. 5 NoneType

In the Python type system,

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
06 is a “first class” type, and for typing purposes,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
98 is an alias for
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
06. If an argument can be
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
98, it has to be declared. You can use
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
10, but if there is only one other type, use
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
11

Use explicit

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
11 instead of implicit
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
11. Earlier versions of PEP 484 allowed
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
14 to be interpreted as
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
15, but that is no longer the preferred behavior

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)
5

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)
6

3. 19. 6 Type Aliases

You can declare aliases of complex types. The name of an alias should be CapWorded. If the alias is used only in this module, it should be _Private

For example, if the name of the module together with the name of the type is too long

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)
7

Other examples are complex nested types and multiple return variables from a function (as a tuple)

3. 19. 7 Ignoring Types

You can disable type checking on a line with the special comment

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
16

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
17 has a disable option for specific errors (similar to lint)

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)
8

3. 19. 8 Typing Variables

If an internal variable has a type that is hard or impossible to infer, specify its type with an annotated assignment - use a colon and type between the variable name and value (the same as is done with function arguments that have a default value)

No:
  result = [complicated_transform(
                x, some_argument=x+1)
            for x in iterable if predicate(x)]

  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]

  return ((x, y, z)
          for x in range(5)
          for y in range(5)
          if x != y
          for z in range(5)
          if y != z)
9

Though you may see them remaining in the codebase (they were necessary before Python 3. 6), do not add any more uses of a
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
18 comment on the end of the line

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
00

3. 19. 9 Tuples vs Lists

Typed lists can only contain objects of a single type. Typed tuples can either have a single repeated type or a set number of elements with different types. Cái sau thường được sử dụng làm kiểu trả về từ một hàm

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
01

3. 19. 10 TypeVars

The Python type system has . The factory function

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
55 is a common way to use them

Example

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
02

A TypeVar can be constrained

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
03

A common predefined type variable in the

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
21 module is
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
21. Use it for multiple annotations that can be
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
22 or
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
23 and must all be the same type

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
04

A TypeVar must have a descriptive name, unless it meets all of the following criteria

  • not externally visible
  • not constrained

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
05

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
06

3. 19. 11 String types

Do not use

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
24 in new code. It’s only for Python 2/3 compatibility

Use

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
23 for string/text data. For code that deals with binary data, use
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
22

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
07

If all the string types of a function are always the same, for example if the return type is the same as the argument type in the code above, use

3. 19. 12 Imports For Typing

For symbols from the

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
21 and
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
22 modules used to support static analysis and type checking, always import the symbol itself. This keeps common annotations more concise and matches typing practices used around the world. You are explicitly allowed to import multiple specific classes on one line from the
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
21 and
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
22 modules. Ex

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
08

Given that this way of importing adds items to the local namespace, names in

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
21 or
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
22 should be treated similarly to keywords, and not be defined in your Python code, typed or not. If there is a collision between a type and an existing name in a module, import it using
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
33

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
09

Prefer to use built-in types as annotations where available. Python supports type annotations using parametric container types via PEP-585, introduced in Python 3. 9

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
10

NOTE. Users of Apache Beam should continue to import parametric containers from

Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
21

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
11

3. 19. 13 Conditional Imports

Use conditional imports only in exceptional cases where the additional imports needed for type checking must be avoided at runtime. This pattern is discouraged; alternatives such as refactoring the code to allow top level imports should be preferred

Imports that are needed only for type annotations can be placed within an

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
35 block

  • Conditionally imported types need to be referenced as strings, to be forward compatible with Python 3. 6 where the annotation expressions are actually evaluated
  • Only entities that are used solely for typing should be defined here; this includes aliases. Otherwise it will be a runtime error, as the module will not be imported at runtime
  • The block should be right after all the normal imports
  • There should be no empty lines in the typing imports list
  • Sort this list as if it were a regular imports list

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    12

3. 19. 14 Circular Dependencies

Circular dependencies that are caused by typing are code smells. Such code is a good candidate for refactoring. Although technically it is possible to keep circular dependencies, various build systems will not let you do so because each module has to depend on the other

Replace modules that create circular dependency imports with

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
01. Set an with a meaningful name, and use the real type name from this module (any attribute of Any is Any). Alias definitions should be separated from the last import by one line

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
13

3. 19. 15 Generics

When annotating, prefer to specify type parameters for generic types; otherwise,

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
14

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
15

If the best type parameter for a generic is

Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
01, make it explicit, but remember that in many cases might be more appropriate

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
16

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
17

4 Parting Words

BE CONSISTENT

If you’re editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around all their arithmetic operators, you should too. If their comments have little boxes of hash marks around them, make your comments have little boxes of hash marks around them too

The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you’re saying rather than on how you’re saying it. We present global style rules here so people know the vocabulary, but local style is also important. If code you add to a file looks drastically different from the existing code around it, it throws readers out of their rhythm when they go to read it. Avoid this