Ví dụ python kế thừa đa cấp

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

To help you format code correctly, we’ve created a settings file for Vim. For Emacs, the default settings should be fine

Nhiều nhóm sử dụng trình định dạng tự động yapf để tránh tranh cãi về định dạng

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
14 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
14 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
14 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
14 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
14 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
19) 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
20

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
14 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
22 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
23

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
24’ 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
25’, 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
24’. 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
27 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
28 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
29 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
30

2. 2. 3 Cons

Module names can still collide. Some module names are inconveniently long

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
    
    31 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
    
    32 where
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    30 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
    
    34 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
    
    35 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
    
    34 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
    
    34 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
    
    34 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
    
    39 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
    
    40 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
    
    41 for
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    42)

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
43 may be imported as follows

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

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

Miễn trừ từ quy tắc này

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

2. 3 Packages

Import each module using the full pathname location of the module

2. 3. 1 Ưu điểm

Tránh xung đột về tên mô-đun hoặc nhập sai do đường dẫn tìm kiếm mô-đun không như tác giả mong đợi. Làm cho nó dễ dàng hơn để tìm các mô-đun

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

Làm cho việc triển khai mã trở nên khó khăn hơn vì bạn phải sao chép hệ thống phân cấp gói. Không thực sự là một vấn đề với các cơ chế triển khai hiện đại

2. 3. 3 Quyết định

Tất cả mã mới phải nhập từng mô-đun theo tên gói đầy đủ của nó

Nhập khẩu phải như sau

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

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

(giả sử tệp này tồn tại trong

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
44 nơi mà
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
45 cũng tồn tại)

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

Thư mục chứa tệp nhị phân chính không nên được coi là trong

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
46 mặc dù điều đó xảy ra trong một số môi trường. Trong trường hợp này, mã phải giả định rằng
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
47 đề cập đến bên thứ ba hoặc gói cấp cao nhất có tê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
48, không phải là 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
45 cục bộ

2. 4 ngoại lệ

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
    
    50 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
    
    51 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
    
    51 is used to ensure internal correctness, not to enforce correct usage nor to indicate that some unexpected event occurred. If an exception is desired in the latter cases, use a raise statement. For example

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

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

  • Libraries or packages may define their own exceptions. When doing so they must inherit from an existing exception class. Exception names should end in

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    53 and should not introduce repetition (
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    54)

  • Never use catch-all

    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, or catch
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    56 or
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    57, unless you are

    • re-raising the exception, or
    • creating an isolation point in the program where exceptions are not propagated but are recorded and suppressed instead, such as protecting a thread from crashing by guarding its outermost block

    Python is very tolerant in this regard and

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    55 will really catch everything including misspelled names, sys. exit() calls, Ctrl+C interrupts, unittest failures and all kinds of other exceptions that you simply don’t want to catch

  • Minimize the amount of code in a

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    59/
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    60 block. The larger the body of the
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    59, the more likely that an exception will be raised by a line of code that you didn’t expect to raise an exception. In those cases, the
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    59/
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    60 block hides a real error

  • Use the

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    64 clause to execute code whether or not an exception is raised in the
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    59 block. This is often useful for cleanup, i. e. , đóng một tập tin

2. 5 Global variables

Avoid global variables

2. 5. 1 Definition

Variables that are declared at the module level or as class attributes

2. 5. 2 Pros

Occasionally useful

2. 5. 3 Cons

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

Avoid global variables

If needed, global variables should be declared at the module level and made internal to the module 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
24 to the name. External access to global variables must be done through public module-level functions. See Naming below

While module-level constants are technically variables, they 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
67. Constants must be named using all caps with underscores. See Naming 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. Very ADT-y. Commonly used for implementing decorators

2. 6. 3 Cons

Nested functions and classes cannot be directly tested. Nesting can make the outer function longer and less readable

2. 6. 4 Decision

They are fine with some caveats. Avoid nested functions or classes except when closing over a local value other than

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
68 or
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
69. 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 vùng chứa và trình vòng 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
70,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
71 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
72

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 tránh hoàn toàn 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
73, 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
73 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

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

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

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

The default iterators and operators are simple and efficient. 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 sạch

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
70 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
71 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
72

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

Tiệ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 nó là một hàm lồng nhau 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
78 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
79 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
80

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
81

2. 11. 2 Pros

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
82. 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
83 đượ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
84 đượ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
84 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 đặt các thuộc tính yêu cầu tính toán hoặc logic tầm 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 getter và setter
  • 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 một thuộc tính để lấy và đặt mộ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 (thay vào đó hãy đặt thuộc tính công khai). 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 trình trang trí

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

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
87 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 tất cả các 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
88 đề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
89 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
90. 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
    
    91 (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
    
    92) để 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
    
    93. 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
    
    93 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
    
    87 bằng cách 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. 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
    
    97 để 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
    
    87 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
    
    93 thì hãy xâu chuỗi các biểu thức, chẳng hạn như
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    200

  • Đố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 đó,

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    201 và
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    202 được ưu tiên hơn so 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
    
    203 và
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    204 tương ứng

  • Khi xử lý các số nguyên, sai ẩn 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
    
    93 thành 0). Bạn có thể so sánh một giá trị đã biết là một số nguyên (và không phải là kết quả 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
    
    206) 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

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    207 (tôi. e. ,
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    208 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

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    209 khi kiểm tra sự trống rỗng của 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
    
    210 (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
    
    211)

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,

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
212 sẽ in
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
213, không phải
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
214

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
215 và hạn chế 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
216

2. 17. 1 Định nghĩa

Trình trang trí cho Hàm và Phương thức (a. k. một “ký hiệu

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
217”). 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
86, đượ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
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
219, điều này

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

tương đương 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
21

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ừ

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
220 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 phần chính để thảo luận thêm

Không bao giờ 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
215 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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
216 khi viết hàm tạo có tên hoặc 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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
223 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
224 được triển khai dưới dạng các 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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
225 của mô-đun Hàng đợi làm cách ưu tiên để giao tiếp dữ liệu giữa các luồng. Nếu không, hãy sử dụng mô-đun luồng và các nguyên hàm khóa của nó. Ưu tiên các biến điều kiện và
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
226 thay vì sử dụng các khóa cấp thấp hơn

2. 19 Power Features

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
227), sửa đổi nội bộ hệ thống, phương pháp
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
228 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ụ:

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

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

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
232 đượ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 có các tính năng bị ẩn đằng sau lần nhập
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
234, 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

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

Để 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 báo cáo nhập khẩu

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

Chú thích loại có thể có trong nguồn hoặc trong tệp pyi còn sơ khai. 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 hàm hoặc đối số phương thức và giá trị trả về

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

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ác Tính năng mạnh mẽ 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 trình kiểm tra loại có thể làm giảm khả năng sử dụng các Tính năng Nguồn 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 đó, 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ã khi thích hợp

3 quy tắc kiểu Python

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

Không kết thúc dòng của bạn bằng dấu chấm phẩy và không sử dụng dấu chấm phẩy để đặt hai câu lệnh trên cùng một dòng

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

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
237 yêu cầu ba trình quản lý ngữ cảnh trở lên

Sử dụng cách nối dòng ẩn của Python bên trong dấu ngoặc đơn, dấu ngoặc và dấu ngoặc nhọn. 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

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

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

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

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

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

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

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
237 có biểu thức kéo dài từ ba dòng trở lên. Đối với hai dòng biểu thức, hãy sử dụng câu lệnh
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
237 lồng nhau

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

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

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

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ộ

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

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

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 ví dụ về độ dài dòng) hoặc sử dụng thụt lề 4 khoảng trắng treo. Closing (round, square or curly) brackets can be placed at the end of the expression, or on separate lines, but then should be indented the same as the line with the corresponding opening bracket

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

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

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
240,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
241 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
242 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ã Python YAPF 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ó ____ ______3243 sau phần tử cuối cùng

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

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 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
244 và phương thức đầu tiên. Không có dòng trống nào sau 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
245. 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

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

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

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

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

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

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

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

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

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 (

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
246), so sánh (
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
247) và Booleans (
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
248). Sử dụ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 (
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
249,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
250,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
251,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
252,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
253,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
254,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
255,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
217)

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
246 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ệ. khi có chú thích loại, hãy sử dụng khoảng trắng xung quanh
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
246 cho giá trị tham số mặc định

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

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

Không sử dụng khoảng trắng để sắp xếp theo chiều dọ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

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

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

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

3. 7 dòng Shebang

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
262 không cần bắt đầu bằng 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
263. Bắt đầu tệp chính của chương trình 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
264 (để hỗ trợ virtualenv) 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
265 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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
266 của đối tượng và được sử dụng bởi
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
220. (Hãy thử chạy
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
220 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
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
269 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

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

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 hoặc trình tạo

Một hàm phải có một chuỗi tài liệu, trừ khi nó đáp ứng tất cả các tiêu chí sau

  • không thể nhìn thấy bên ngoài
  • rất ngắn
  • 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 phải là kiểu mô tả (______3270) thay vì kiểu mệnh lệnh (

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
271). 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
86 phải sử dụng cùng kiểu với chuỗi tài liệu cho thuộc tính hoặc đối số 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
273, 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
274)

Một phương thức ghi đè một phương thức từ mộ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ư

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

lập luận. 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
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
276 (danh sách đối số có độ dài thay đổi) và/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
277 (đối số từ khóa tùy ý), thì chúng phải được liệt kê là
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
276 và
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
277. trả lại. (hoặc Sản lượng. cho trình tạo) 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.
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
280) và câu mở đầu đủ để mô tả giá trị trả về. Không bắt chước 'kiểu NumPy' (ví dụ), kiểu này thường ghi lại giá trị trả về của bộ dữ liệu như thể đó là nhiều giá trị trả về với các tên riêng lẻ (không bao giờ đề cập đến bộ dữ liệu). Thay vào đó, hãy mô tả một giá trị trả về như. “Trả về. Một bộ (mat_a, mat_b), trong đó mat_a là …, và…”. Các tên phụ trợ trong chuỗi tài liệu không nhất thiết phải tương ứng với bất kỳ tên nội bộ nào được sử dụng trong thân hàm (vì chúng không phải là một phần của API). tăng. Liệt kê tất cả các ngoại lệ có liên quan đến giao diện theo sau là mô tả. Sử dụng tên ngoại lệ tương tự + dấu hai chấm + dấu cách hoặc dòng mới và kiểu thụt lề treo như được mô tả trong Args. Bạn không nên ghi lại các trường hợp ngoại lệ được nêu ra nếu API được chỉ định trong chuỗi tài liệu bị vi phạm (vì điều này nghịch lý sẽ tạo ra hành vi vi phạm phần API của API)

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

Tương tự, biến thể này trên

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
281 có ngắt dòng cũng được cho phép

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

3. 8. 4 lớp

Các lớp nên có một chuỗi tài liệu bên dưới định nghĩa lớp mô tả lớp. Nếu lớp của bạn có các thuộc tính công khai, chúng phải được ghi lại ở đây trong phần

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
282 và tuân theo cùng định dạng như phần
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
283 của 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
49

Tất cả các chuỗi tài liệu lớp phải bắt đầu bằng một bản tóm tắt một dòng mô tả nội dung mà thể hiện của lớp đại diện. Điều này ngụ ý rằng các lớp con 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
56 cũng nên mô tả ngoại lệ đại diện cho cái gì chứ không phải bối cảnh mà nó có thể xảy ra. Chuỗi tài liệu lớp không được lặp lại thông tin không cần thiết, chẳng hạn như lớp là một lớp

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

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

3. 8. 5 Block and Inline Comments

Nơi cuối cùng để có nhận xét là ở những phần phức tạp của mã. Nếu bạn phải giải thích nó trong lần đánh giá mã tiếp theo, bạn nên bình luận ngay bây giờ. Các hoạt động phức tạp nhận được một vài dòng nhận xét trước khi các hoạt động bắt đầu. Những người không rõ ràng nhận được bình luận ở cuối 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
72

Để cải thiện mức độ dễ đọc, các nhận xét này phải bắt đầu cách mã ít nhất 2 dấu cách với ký tự nhận xét

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
260, theo sau là ít nhất một khoảng trắng trước văn bản của chính nhận xét đó

Mặt khác, không bao giờ mô tả mã. Giả sử người đọc mã biết Python (mặc dù không phải thứ bạn đang cố gắng làm) tốt hơn bạn

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

3. 8. 6 Dấu câu, Chính tả và Ngữ pháp

Chú ý đến dấu câu, chính tả và ngữ pháp;

Nhận xét phải dễ đọc như văn bản tường thuật, với cách viết hoa và dấu câu thích hợp. Trong nhiều trường hợp, các câu hoàn chỉnh dễ đọc hơn các đoạn câu. Các chú thích ngắn hơn, chẳng hạn như chú thích ở cuối dòng mã, đôi khi có thể kém trang trọng hơn, nhưng bạn nên nhất quán với phong cách của mình

Mặc dù có thể khó chịu khi người đánh giá mã chỉ ra rằng bạn đang sử dụng dấu phẩy trong khi lẽ ra bạn nên sử dụng dấu chấm phẩy, nhưng điều rất quan trọng là mã nguồn phải duy trì mức độ rõ ràng và dễ đọc cao. Dấu chấm câu, chính tả và ngữ pháp phù hợp giúp đạt được mục tiêu đó

3. 10 Dây

Sử dụng chuỗi f, toán tử

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
254 hoặc phương pháp
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
287 để định dạng chuỗi, ngay cả khi các tham số đều là chuỗi. Sử dụng khả năng phán đoán tốt nhất của bạn để quyết định giữa định 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
249 và chuỗi

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

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

Tránh sử dụng các toán tử

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
249 và
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
290 để tích lũy một chuỗi trong một vòng lặp. Trong một số điều kiện, tích lũy một chuỗi với phép cộng có thể dẫn đến thời gian chạy bậc hai thay vì tuyến tính. Mặc dù các tích lũy phổ biến thuộc loại này có thể được tối ưu hóa trên CPython, nhưng đó là chi tiết triển khai. Các điều kiện áp dụng tối ưu hóa không dễ dự đoán và có thể thay đổi. Thay vào đó, hãy thêm từng chuỗi con vào danh sách và
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
291 danh sách sau khi vòng lặp kết thúc hoặc ghi từng chuỗi con vào bộ đệm
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
292. Các kỹ thuật này luôn có độ phức tạp thời gian chạy tuyến tính được khấu hao

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

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

Hãy nhất quán với sự lựa chọn của bạn về ký tự trích dẫn chuỗi trong một tệp. Chọn

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
293 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
294 và gắn bó với nó. Bạn có thể sử dụng ký tự trích dẫn khác trên một chuỗi để tránh phải ký tự trích dẫn thoát dấu gạch chéo ngược trong chuỗi

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

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

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
269 cho chuỗi nhiều dòng 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
296. Các dự án có thể chọ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
296 cho tất cả các chuỗi nhiều dòng không phải chuỗi doc nếu và chỉ khi chúng cũng 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
293 cho các chuỗi thông thường. Docstrings phải 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
269 bất kể

Các chuỗi nhiều dòng không chạy với phần thụt đầu dòng của phần còn lại của chương trình. Nếu bạn cần tránh nhúng thêm khoảng trắng vào chuỗi, hãy sử dụng chuỗi một dòng được nối hoặc chuỗi nhiều dòng 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
300 để xóa khoảng trắng ban đầu trên mỗi dòng

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

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

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

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

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

3. 10. 1 nhật ký

Đối với các chức năng ghi nhật ký yêu cầu một chuỗi mẫu (với %-placeholders) làm đối số đầu tiên của chúng. Luôn gọi chúng bằng một chuỗi ký tự (không phải chuỗi f. ) as their first argument with pattern-parameters as subsequent arguments. Một số triển khai ghi nhật ký thu thập chuỗi mẫu chưa được mở rộng dưới dạng trường có thể truy vấn. Nó cũng ngăn việc dành thời gian hiển thị thông báo mà không có trình ghi nhật ký nào được định cấu hình để xuất

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

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

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

3. 10. 2 thông báo lỗi

Thông báo lỗi (chẳng hạn như. chuỗi thông báo về các trường hợp ngoại lệ như

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
50 hoặc thông báo được hiển thị cho người dùng) phải tuân theo ba nguyên tắc

  1. Thông báo cần khớp chính xác với tình trạng lỗi thực tế

  2. Các phần được nội suy cần phải luôn được xác định rõ ràng như vậy

  3. Chúng nên cho phép xử lý tự động đơn giản (e. g. mò mẫm)

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

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

3. 11 Tệp, Ổ cắm và Tài nguyên có trạng thái tương tự

Đóng các tệp và ổ cắm một cách rõ ràng khi hoàn thành với chúng. Quy tắc này tự nhiên mở rộng cho các tài nguyên có thể đóng sử dụng ổ cắm bên trong, chẳng hạn như kết nối cơ sở dữ liệu và cả các tài nguyên khác cần được đóng theo cách tương tự. Chỉ kể tên một vài ví dụ, điều này cũng bao gồm ánh xạ mmap, đối tượng Tệp h5py và matplotlib. cửa sổ hình pyplot

Để các tệp, ổ cắm hoặc các đối tượng trạng thái khác mở một cách không cần thiết có nhiều nhược điểm

  • Chúng có thể tiêu tốn tài nguyên hệ thống hạn chế, chẳng hạn như bộ mô tả tệp. Mã xử lý nhiều đối tượng như vậy có thể làm cạn kiệt các tài nguyên đó một cách không cần thiết nếu chúng không được trả lại hệ thống ngay sau khi sử dụng
  • Việc giữ các tệp đang mở có thể ngăn các hành động khác như di chuyển hoặc xóa chúng hoặc ngắt kết nối hệ thống tệp
  • Các tệp và ổ cắm được chia sẻ trong toàn bộ chương trình có thể vô tình được đọc từ hoặc ghi vào sau khi đóng một cách hợp lý. Nếu chúng thực sự bị đóng, các nỗ lực đọc hoặc ghi từ chúng sẽ đưa ra các ngoại lệ, làm cho vấn đề được biết đến sớm hơn

Hơn nữa, trong khi các tệp và ổ cắm (và một số tài nguyên hoạt động tương tự) tự động đóng khi đối tượng bị hủy, thì việc ghép thời gian tồn tại của đối tượng với trạng thái của tài nguyên là một cách thực hành kém.

  • Không có gì đảm bảo khi nào bộ thực thi sẽ thực sự gọi 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
    
    228. Các triển khai Python khác nhau sử dụng các kỹ thuật quản lý bộ nhớ khác nhau, chẳng hạn như bộ sưu tập rác bị trì hoãn, điều này có thể làm tăng tuổi thọ của đối tượng một cách tùy ý và vô thời hạn
  • Các tham chiếu không mong muốn đến tệp, e. g. trong toàn cầu hoặc theo dõi ngoại lệ, có thể giữ nó lâu hơn dự định

Việc dựa vào các công cụ hoàn thiện để thực hiện dọn dẹp tự động có các tác dụng phụ có thể quan sát được đã được khám phá lại nhiều lần để dẫn đến các vấn đề lớn, qua nhiều thập kỷ và nhiều ngôn ngữ (xem e. g. bài viết này cho Java)

Cách ưu tiên để quản lý tệp và các tài nguyên tương tự là sử dụng câu lệnh

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

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

Đối với các đối tượng giống như tệp không hỗ trợ câu lệnh

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
237, hãy 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
305

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

Trong những trường hợp hiếm hoi khi quản lý tài nguyên dựa trên ngữ cảnh là không khả thi, tài liệu mã phải giải thích rõ ràng cách quản lý thời gian tồn tại của tài nguyên

Sử dụng nhận xét

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
306 cho mã tạm thời, giải pháp ngắn hạn hoặc đủ tốt nhưng không hoàn hảo

Nhận xét

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
306 bắt đầu bằng từ
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
306 viết hoa toàn bộ và một mã định danh ngữ cảnh được đặt trong ngoặc đơn. Lý tưởng nhất là tham chiếu lỗi, đôi khi là tên người dùng. Một tài liệu tham khảo lỗi như
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
309 là thích hợp hơn, bởi vì các lỗi được theo dõi và có các nhận xét tiếp theo, trong khi các cá nhân di chuyển xung quanh và có thể mất ngữ cảnh theo thời gian.
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
306 được theo sau bởi một lời giải thích về những việc phải làm

Mục đích là để có định 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
306 nhất quán có thể tìm kiếm để biết cách lấy thêm chi tiết.
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
306 không phải là cam kết rằng người được giới thiệu sẽ khắc phục sự cố. Do đó, khi bạn tạo 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
306 với tên người dùng, thì hầu như tên người dùng của bạn luôn được cung cấp

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

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
306 của bạn có dạng “Vào một ngày trong tương lai, hãy làm điều gì đó”, hãy đảm bảo rằng bạn bao gồm một ngày rất cụ thể (“Khắc phục trước tháng 11 năm 2009”) hoặc một sự kiện rất cụ thể (“Xóa mã này khi tất cả khách hàng có thể xử lý phản hồi XML. ”) mà những người bảo trì mã trong tương lai sẽ hiểu

3. 13 Nhập định dạng

Nhập khẩu nên được trên các dòng riêng biệt;

E. g

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

Các mục nhập luôn được đặt ở đầu tệp, ngay sau bất kỳ nhận xét và chuỗi tài liệu nào của mô-đun cũng như trước các hằng số và toàn cầu của mô-đun. Nhập khẩu nên được nhóm từ chung chung nhất đến ít chung chung nhất

  1. Báo cáo nhập khẩu trong tương lai của Python. For example

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

    Xem ở trên để biết thêm thông tin về những

  2. Nhập thư viện chuẩn Python. Ví dụ

  3. nhập mô-đun hoặc gói của bên thứ ba. Ví dụ

  4. Nhập gói con kho lưu trữ mã. Ví dụ

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

  5. không dùng nữa. nhập dành riêng cho ứng dụng là một phần của gói con cấp cao nhất giống như tệp này. Ví dụ

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

    Bạn có thể tìm thấy mã Google Python Style cũ hơn để thực hiện việc này, nhưng nó không còn cần thiết nữa. Mã mới được khuyến khích không bận tâm với điều này. Đơn giản chỉ cần xử lý các lần nhập gói phụ dành riêng cho ứng dụng giống như các lần nhập gói phụ khác

Trong mỗi nhóm, các mục nhập phải được sắp xếp theo thứ tự từ điển, bỏ qua trường hợp, theo đường dẫn gói đầy đủ của mỗi mô-đun (_______3317 trong _

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
318). Mã có thể tùy chọn đặt một dòng trống giữa các phần nhập

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

3. 14 Tuyên bố

Nói chung chỉ có một tuyên bố trên mỗi dòng

Tuy nhiên, bạn chỉ có thể đặt kết quả của một bài kiểm tra trên cùng một dòng với bài kiểm tra nếu toàn bộ câu lệnh nằm trên một dòng. Đặc biệt, bạn không bao giờ có thể làm như vậy 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
59/
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
60 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 và
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
60 không thể vừa trên cùng một dòng và bạn chỉ có thể làm như vậy 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
323 nếu không có
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
324

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

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ý

Ví dụ: nếu một cặp getters/setters chỉ đọc và ghi một thuộc tính nội bộ, thì thuộc tính nội bộ sẽ được công khai thay thế. Để 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ác thuộc tính 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 và setters phải tuân theo Nguyên tắc đặt tên, chẳng hạn như

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

Nếu hành vi trong quá khứ cho phép truy cập thông qua một thuộc tính, không liên kết các hàm getter/setter mới với thuộc tính. Bất kỳ mã nào vẫn đang cố truy cập vào biến theo phương thức cũ sẽ bị hỏng rõ ràng để chúng nhận thức được sự thay đổi về độ phức tạp

3. 16 đặt tên

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
327,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
328,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
329,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
330,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
331,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
332,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
333,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
334,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
335,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
336,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
337,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
338,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
339

Tên hàm, tên biến và tên tệp phải mang tính mô tả; . Đặc biệt, không sử dụng các từ viết tắt mơ hồ hoặc không quen thuộc với người đọc bên ngoài dự án của bạn và không viết tắt bằng cách xóa các chữ cái trong một từ

Always use a

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

3. 16. 1 Names to Avoid

  • single character names, except for specifically allowed cases

    • counters or iterators (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
      
      341,
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      342,
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      343,
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      344, et al. )
    • def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      345 as an exception identifier in
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      346 statements
    • def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      347 as a file handle in
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      237 statements
    • private
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      349s with no constraints (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
      
      350,
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      351,
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      352)

    Please be mindful not to abuse single-character naming. Generally speaking, descriptiveness should be proportional to the name’s scope of visibility. 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
    
    341 might be a fine name for 5-line code block but within multiple nested scopes, it is likely too vague

  • dashes (

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    250) in any package/module name

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

  • offensive terms

  • names that needlessly include the type of the variable (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
    
    356)

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
    
    24) has some support for protecting module variables and functions (linters will flag protected member access)

  • Prepending a double underscore (

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

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

  • Underscores may appear in unittest method names starting with

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    361 to separate logical components of the name, even if those components use CapWords. One possible pattern is
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    362; 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
    
    363 is okay. There is no One Correct Way to name test methods

3. 16. 3 File Naming

Python filenames must have a

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
262 extension and must not contain dashes (
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
250). 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
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
366

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

TypePublicInternalPackages
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
367Modules
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
367
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
369Classes
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
370
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
371Exceptions
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
370Functions
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
373
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
374Global/Class Constants
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
375
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
376Global/Class Variables
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
367
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
369Instance Variables
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
367
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
369 (protected)Method Names
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
373
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
374 (protected)Function/Method Parameters
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
367Local Variables
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
367

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
385 for public APIs, which are much more likely to be encountered out of context

3. 17 Main

In Python,

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
220 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
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
387 function, and your code should always check
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
388 before executing your main program, so that it is not executed when the module is imported

When using absl, use

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

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

Otherwise, use

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

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

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

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
    
    68, or
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    69 if it is necessary for proper type information. 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
    
    91

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

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    393 (where
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    93 is the only valid option)

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

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

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

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

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

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

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

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

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

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

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

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

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

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)

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

Nếu một tên và loại quá dài, hãy cân nhắc sử dụng bí danh cho loại. The last resort is to break after the colon and indent by 4

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

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

3. 19. 3 Tuyên bố chuyển tiếp

Nếu bạn cần sử dụng một tên lớp từ cùng một mô-đun chưa được xác định – ví dụ: nếu bạn cần lớp bên trong khai báo lớp hoặc nếu bạn sử dụng một lớp được xác định bên dưới – hãy 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
398 cho các trường hợp đơn giản hoặc 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
00

3. 19. 4 giá trị mặc định

Theo PEP-008, chỉ sử dụng khoảng trắng xung quanh

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
246 cho các đối số có cả chú thích loại và giá trị mặc định

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

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

3. 19. 5 NoneType

In the Python type system,

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
400 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
93 is an alias for
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
400. 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
93, it has to be declared. You can use
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
404, but if there is only one other type, use
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
405

Use explicit

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
405 instead of implicit
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
405. Earlier versions of PEP 484 allowed
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
408 to be interpreted as
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
409, but that is no longer the preferred behavior

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

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

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

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

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

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
411 has a disable option for specific errors (similar to lint)

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. 8 Typing Variables

Annotated AssignmentsIf 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)

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

Type CommentsThough you may see them remaining in the codebase (they were necessary before Python 3. 6), do not add any more uses of a
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
412 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
08

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. The latter is commonly used as the return type from a function

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

3. 19. 10 TypeVars

The Python type system has generics. Chức năng nhà máy

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
349 là một cách phổ biến để sử dụng chúng

Example

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

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
01

A common predefined type variable in the

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
315 module is
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
415. Use it for multiple annotations that 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
416 or
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
417 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
02

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

  • không thể nhìn thấy bên ngoài
  • 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
03

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

3. 19. 11 String types

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
418 in new code. It’s only for Python 2/3 compatibility

Use

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
417 for string/text data. For code that deals with binary data, use
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
416

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

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 AnyStr

3. 19. 12 Imports For Typing

For symbols from the

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
315 and
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
316 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
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
315 and
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
316 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
06

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
315 or
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
316 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
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
427

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

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
428 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
    
    08

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
395. Đặt bí danh có tên có ý nghĩa và sử dụng tên loại thực từ mô-đun này (bất kỳ thuộc tính nào của Any là 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
09

3. 19. 15 Generics

When annotating, prefer to specify type parameters for generic types; otherwise, the generics’ parameters will be assumed to be

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

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

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

If the best type parameter for a generic is

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
395, make it explicit, but remember that in many cases
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
349 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
12

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

4 Lời Chia Tay

BE CONSISTENT

If you’re editing code, take a few minutes to look at the code around you and determine its style. Nếu họ sử dụng khoảng trắng xung quanh tất cả các toán tử số học của họ, thì bạn cũng nên. Nếu nhận xét của họ có các hộp dấu thăng nhỏ xung quanh, hãy làm cho nhận xét của bạn cũng có các hộp dấu thăng nhỏ xung quanh chúng

Mục đích của việc có các hướng dẫn về phong cách là có một vốn từ vựng chung về viết mã để mọi người có thể tập trung vào những gì bạn đang nói hơn là vào cách bạn nói. We present global style rules here so people know the vocabulary, but local style is also important. Nếu mã bạn thêm vào một tệp trông khác hẳn so với mã hiện có xung quanh nó, nó sẽ khiến người đọc mất nhịp khi họ đọc nó. Tránh điều này