Danh sách động python

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

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

2 Python Language Rules

2. 1 Lint

Run

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

2. 1. 1 Definition

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
18 là một công cụ để tìm lỗi và các vấn đề về kiểu dáng trong mã nguồn Python. Nó tìm thấy các vấn đề thường được trình biên dịch bắt gặp đối với các ngôn ngữ kém năng động hơn như C và C++. Do tính chất động của Python, một số cảnh báo có thể không chính xác;

2. 1. 2 Ưu điểm

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

2. 1. 3 Cons

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

2. 1. 4 Decision

Make sure you run

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

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

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

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

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

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

You can get a list of

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

To get more information on a particular message, use

Prefer

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

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

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

Other common forms of suppressing this warning include using ‘

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

2. 2 nhập khẩu

Use

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

2. 2. 1 Definition

Reusability mechanism for sharing code from one module to another

2. 2. 2 Pros

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

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

2. 2. 3 Cons

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

Ví dụ: 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
47 có thể được nhập 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
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

Exemptions from this rule

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

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

2. 3. 2 Cons

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

2. 3. 3 Decision

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

Imports should be as follows

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

(assume this file lives in

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

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

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

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

2. 4 Exceptions

Exceptions are allowed but must be used carefully

2. 4. 1 Definition

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

2. 4. 2 Pros

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

2. 4. 3 Cons

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

2. 4. 4 Decision

Exceptions must follow certain conditions

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

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    54 to indicate a programming mistake like a violated precondition (such as if you were passed a negative number but required a positive one). Do not use
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    55 statements for validating argument values of a public API.
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    55 is used to ensure internal correctness, not to enforce correct usage nor to indicate that some unexpected event occurred. 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
    
    57 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
    
    58)

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

    • tăng lại ngoại lệ, hoặc
    • 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 rất khoan dung về vấn đề này và

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

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

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

  • Sử dụng mệnh đề

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

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

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

2. 5. 1 Định nghĩa

Các giá trị cấp mô-đun hoặc thuộc tính lớp có thể bị thay đổi trong quá trình thực thi chương trình

2. 5. 2 Ưu điểm

Thỉnh thoảng hữu ích

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

  • Phá vỡ đóng gói. Thiết kế như vậy có thể gây khó khăn cho việc đạt được các mục tiêu hợp lệ. Ví dụ: nếu trạng thái chung được sử dụng để quản lý kết nối cơ sở dữ liệu, thì việc kết nối với hai cơ sở dữ liệu khác nhau cùng một lúc (chẳng hạn như đối với sự khác biệt về tính toán trong quá trình di chuyển) sẽ trở nên khó khăn. Các vấn đề tương tự dễ dàng phát sinh với các cơ quan đăng ký toàn cầu

  • Có khả năng thay đổi hành vi của mô-đun trong quá trình nhập, vì việc gán cho các biến toàn cục được thực hiện khi mô-đun được nhập lần đầu

2. 5. 4 Quyết định

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

Trong những trường hợp hiếm hoi khi sử dụng trạng thái toàn cầu được đảm bảo, các thực thể toàn cầu có thể thay đổi phải được khai báo ở cấp độ mô-đun hoặc dưới dạng thuộc tính lớp và được đặt bên trong bằng cách thêm 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
28 vào tên. Nếu cần, quyền truy cập bên ngoài vào trạng thái toàn cầu có thể thay đổi phải được thực hiện thông qua các hàm công khai hoặc phương thức lớp. Xem cách đặt tên bên dưới. Vui lòng giải thích lý do thiết kế tại sao trạng thái chung có thể thay đổi đang được sử dụng trong nhận xét hoặc tài liệu được liên kết từ nhận xét

Hằng số cấp mô-đun được cho phép và khuyến khích. 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
71 cho hằng số sử dụng nội bộ 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 cho hằng số API công khai. Các hằng số phải được đặt tên bằng cách sử dụng tất cả các chữ hoa có dấu gạch dưới. Xem cách đặt tên bên dưới

2. 6 Các lớp và hàm lồng nhau/cục bộ/bên trong

Các hàm hoặc lớp cục bộ lồng nhau vẫn ổn khi được sử dụng để đóng trên một biến cục bộ. Các lớp bên trong vẫn ổn

2. 6. 1 Định nghĩa

Một lớp có thể được định nghĩa bên trong một phương thức, hàm hoặc lớp. Một hàm có thể được định nghĩa bên trong một phương thức hoặc hàm. Các hàm lồng nhau có quyền truy cập chỉ đọc vào các biến được xác định trong phạm vi kèm theo

2. 6. 2 Ưu điểm

Cho phép định nghĩa các lớp và chức năng tiện ích chỉ được sử dụng bên trong phạm vi rất hạn chế. Rất ADT-y. Thường được sử dụng để thực hiện trang trí

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

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

2. 6. 4 Quyết định

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

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

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

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

2. 7. 1 Định nghĩa

Khả năng hiểu List, Dict và Set cũng như các biểu thức trình tạo cung cấp một cách ngắn gọn và hiệu quả để tạo các loại 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
75,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
76 hoặc
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
77

2. 7. 2 Ưu điểm

Việc hiểu đơn giản có thể rõ ràng và đơn giản hơn các kỹ thuật tạo chính tả, danh sách hoặc tập hợp khác. Biểu thức trình tạo có thể rất hiệu quả, vì chúng 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
78, biểu thức bộ lọc. Nhiều mệnh đề
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
78 hoặc biểu thức bộ lọc không được phép. Thay vào đó, hãy sử dụng các vòng lặp khi mọi thứ trở nên phức tạp hơn

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. 8 Iterator và Operator mặc định

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

2. 8. 1 Định nghĩa

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

2. 8. 2 Ưu điểm

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

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

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

2. 8. 4 Quyết định

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

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

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

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

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

2. 9. 1 Định nghĩa

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

2. 9. 2 Ưu điểm

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

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

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

2. 9. 4 Quyết định

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

Nếu trình tạo quản lý một tài nguyên đắt tiền, hãy đảm bảo buộc dọn 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
75 hoặc
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
76 với một
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
77

2. 10. 1 Định nghĩa

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

2. 10. 2 Ưu điểm

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

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

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

2. 11. 1 Định nghĩa

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

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

2. 11. 2 Ưu điểm

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

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

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

2. 11. 4 Quyết định

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

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

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

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

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

2. 12. 1 Định nghĩa

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

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

2. 12. 2 Ưu điểm

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

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

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

2. 12. 4 Quyết định

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

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

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

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

2. 13 thuộc tính

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

2. 13. 1 Định nghĩa

Một cách để gói các lệnh 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
  • Can be used to make an attribute read-only
  • 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
91. 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
92 khi ở trong ngữ cảnh boolean. Một "quy tắc ngón tay cái" nhanh chóng 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
93 đều được đánh giá là sai trong ngữ cảnh boolean

2. 14. 2 Ưu điểm

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

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

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

2. 14. 4 Quyết định

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

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

  • Luôn sử dụng

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    96 (hoặc
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    97) để kiểm tra giá trị
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98. e. g. , khi kiểm tra xem một biến hoặc đối số mặc định là
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98 có được đặt thành một số giá trị khác không. The other value might be a value that’s false in a boolean context

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

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    92 bằng cách sử dụng
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    201. 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
    
    202 để thay thế. Nếu bạn cần phân biệt
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    92 với
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98 thì hãy xâu chuỗi các biểu thức, chẳng hạn như
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    205

  • Đối với các chuỗi (chuỗi, danh sách, bộ dữ liệu), 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
    
    206 và
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    207 đượ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
    
    208 và
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    209 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
    
    98 là 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
    
    211) 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
    
    212 (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
    
    213 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
    
    214 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
    
    215 (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
    
    216)

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
217 sẽ in ra
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
218, 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
219

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

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
222”). Một trình trang trí phổ biến là
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
91, được sử dụng để chuyển đổi các phương thức thông thường thành các thuộc tính được tính toán động. Tuy nhiên, cú pháp của trình trang trí cũng cho phép các trình trang trí do người dùng định nghĩa. Cụ thể, đối với một số chức năng
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
224, đ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
225 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
220 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
221 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
228 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
229 đượ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
230 của mô-đun Hàng đợi làm cách ưa thích để 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
231 thay vì sử dụng các khóa cấp thấp hơn

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

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

2. 19. 1 Định nghĩa

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

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

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
237 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
237 đượ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
239, 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
240 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 đó, các tác giả được khuyến khích thêm nhận xét bằng TODO hoặc liên kết đến lỗi mô tả (các) sự cố hiện đang ngăn cản việc áp dụng chú thích loại trong tệp BUILD hoặc trong chính mã nếu phù hợp

3 quy tắc kiểu Python

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

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

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
242 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 phép 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
242 với ba trình quản lý bối cảnh trở lên. Đối với hai trình quản lý bối cảnh, hãy sử dụng câu lệnh
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
242 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. Dấu ngoặc đóng (tròn, vuông hoặc cong) có thể được đặt ở cuối biểu thức hoặc trên các dòng riêng biệt, nhưng sau đó phải được thụt vào giống như dòng có dấu ngoặc mở tương ứng

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
245,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
246 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
247 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ó ____ ______3248 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 chuỗi tài liệu 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
249 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
250. 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
251), 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
252) 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
253). 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
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
256,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
257,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
258,
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
222)

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
251 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
251 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
264,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
265,
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
251, 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
267 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
268. 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
269 (để 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
270 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 để 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
271 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
225. (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
225 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
274 cho các chuỗi tài liệu (theo PEP 257). A docstring should be organized as a summary line (one physical line not exceeding 80 characters) terminated by a period, question mark, or exclamation point. When writing more (encouraged), this must be followed by a blank line, followed by the rest of the docstring starting at the same cursor position as the first quote of the first line. There are more formatting guidelines for docstrings below

3. 8. 2 Modules

Every file should contain license boilerplate. Choose the appropriate boilerplate for the license used by the project (for example, Apache 2. 0, BSD, LGPL, GPL)

Files should start with a docstring describing the contents and usage of 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
46

3. 8. 2. 1 Test modules

Module-level docstrings for test files are not required. They should be included only when there is additional information that can be provided

Examples include some specifics on how the test should be run, an explanation of an unusual setup pattern, dependency on the external environment, and so on

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

Docstrings that do not provide any new information should not be used

3. 8. 3 Functions and Methods

In this section, “function” means a method, function, generator, or property

A docstring is mandatory for every function that has one or more of the following properties

  • being part of the public API
  • nontrivial size
  • non-obvious logic

A docstring should give enough information to write a call to the function without reading the function’s code. The docstring should describe the function’s calling syntax and its semantics, but generally not its implementation details, unless those details are relevant to how the function is to be used. For example, a function that mutates one of its arguments as a side effect should note that in its docstring. Otherwise, subtle but important details of a function’s implementation that are not relevant to the caller are better expressed as comments alongside the code than within the function’s docstring

The docstring may be descriptive-style (

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
275) or imperative-style (
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
276), but the style should be consistent within a file. The docstring for a
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
91 data descriptor should use the same style as the docstring for an attribute or a function argument (
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
278, rather than
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
279)

A method that overrides a method from a base class may have a simple docstring sending the reader to its overridden method’s docstring, such as

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
280. The rationale is that there is no need to repeat in many places documentation that is already present in the base method’s docstring. However, if the overriding method’s behavior is substantially different from the overridden method, or details need to be provided (e. g. , documenting additional side effects), a docstring with at least those differences is required on the overriding method

Certain aspects of a function should be documented in special sections, listed below. 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. All sections other than the heading should maintain a hanging indent of two or four spaces (be consistent within a file). These sections can be omitted in cases where the function’s name and signature are informative enough that it can be aptly described using a one-line docstring

Args. List each parameter by name. A description should follow the name, and be separated by a colon followed by either a space or newline. If the description is too long to fit on a single 80-character line, use a hanging indent of 2 or 4 spaces more than the parameter name (be consistent with the rest of the docstrings in the file). The description should include required type(s) if the code does not contain a corresponding type annotation. If a function accepts
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
281 (variable length argument lists) and/or
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
282 (arbitrary keyword arguments), they should be listed as
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
281 and
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
282. Returns. (or Yields. for generators)Describe the type and semantics of the return value. If the function only returns None, this section is not required. It may also be omitted if the docstring starts with Returns or 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
285) and the opening sentence is sufficient to describe the return value. Do not imitate ‘NumPy style’ (example), which frequently documents a tuple return value as if it were multiple return values with individual names (never mentioning the tuple). Instead, describe such a return value as. “Returns. A tuple (mat_a, mat_b), where mat_a is …, and …”. The auxiliary names in the docstring need not necessarily correspond to any internal names used in the function body (as those are not part of the API). tăng. List all exceptions that are relevant to the interface followed by a description. Use a similar exception name + colon + space or newline and hanging indent style as described in Args. You should not document exceptions that get raised if the API specified in the docstring is violated (because this would paradoxically make behavior under violation of the API part of the API)

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

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

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
287 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
288 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
70

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

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

3. 8. 5 Block and Inline Comments

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

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

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
265, followed by at least one space before the text of the comment itself

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

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

3. 8. 6 Punctuation, Spelling, and Grammar

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

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

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

3. 10 Dây

Use an f-string, the

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
259 operator, or the
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
292 method for formatting strings, even when the parameters are all strings. Use your best judgment to decide between string formatting options. A single join with
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
254 is okay but do not format with
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
75

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

Avoid using the

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
254 and
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
296 operators to accumulate a string within a loop. In some conditions, accumulating a string with addition can lead to quadratic rather than linear running time. Although common accumulations of this sort may be optimized on CPython, that is an implementation detail. The conditions under which an optimization applies are not easy to predict and may change. Instead, add each substring to a list and
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
297 the list after the loop terminates, or write each substring to an
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
298 buffer. These techniques consistently have amortized-linear run time complexity

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

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

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
299 or
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
300 and stick with it. It is okay to use the other quote character on a string to avoid the need to backslash-escape quote characters within the string

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

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

Prefer

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
274 for multi-line strings rather than
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
302. Projects may choose to use
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
302 for all non-docstring multi-line strings if and only if they also use
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
299 for regular strings. Docstrings must use
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
274 regardless

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

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
306 to remove the initial space on each line

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

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

3. 10. 1 Logging

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

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

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

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

3. 10. 2 Error Messages

Error messages (such as. message strings on exceptions like

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

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

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

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

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

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

3. 11 Files, Sockets, and similar Stateful Resources

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

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

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

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

  • There are no guarantees as to when the runtime will actually invoke the
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    233 method. Different Python implementations use different memory management techniques, such as delayed garbage collection, which may increase the object’s lifetime arbitrarily and indefinitely
  • Unexpected references to the file, e. g. in globals or exception tracebacks, may keep it around longer than intended

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

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

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

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

For file-like objects that do not support the

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

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

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

Use

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
312 comments for code that is temporary, a short-term solution, or good-enough but not perfect

A

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
312 comment begins with the word
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
312 in all caps, and a parenthesized context identifier. Ideally a bug reference, sometimes a username. A bug reference like
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
315 is preferable, because bugs are tracked and have follow-up comments, whereas individuals move around and may lose context over time. The
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
312 is followed by an explanation of what there is to do

The purpose is to have a consistent

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
312 format that can be searched to find out how to get more details. A
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
312 is not a commitment that the person referenced will fix the problem. Thus when you create a
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
312 with a username, it is almost always your own username that is given

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

If your

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
312 is of the form “At a future date do something” make sure that you either include a very specific date (“Fix by November 2009”) or a very specific event (“Remove this code when all clients can handle XML responses. ”) mà những người bảo trì mã trong tương lai sẽ hiểu

3. 13 Imports formatting

Imports should be on separate lines; there are exceptions for

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

E. g

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

Imports are always put at the top of the file, just after any module comments and docstrings and before module globals and constants. Nhập khẩu nên được nhóm từ chung chung nhất đến ít chung chung nhất

  1. Python future import statements. For example

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

    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. third-party module or package imports. Ví dụ

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

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

  5. không dùng nữa. application-specific imports that are part of the same top level sub-package as this file. Ví dụ

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

    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 từ điển, bỏ qua trường hợp, theo đường dẫn gói đầy đủ của mỗi mô-đun (_______3323 trong ____3324). 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
68

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
63/
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
64 vì cả
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
63 và
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
64 đều không thể nằm 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
329 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
330

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

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

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

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ừ

Luôn sử dụng phần mở rộng tên 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
267. Không bao giờ sử dụng dấu gạch ngang

3. 16. 1 Tên cần tránh

  • tên ký tự đơn, ngoại trừ các trường hợp được phép cụ thể

    • bộ đếm hoặc bộ lặp (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
      
      347,
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      348,
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      349,
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      350, 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
      
      351 như một định danh ngoại lệ trong 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
      
      352
    • def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      353 dưới dạng xử lý tệp trong 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
      
      242
    • các
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      355 riêng tư không có ràng buộc (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
      
      356,
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      357,
      def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
          del beans, eggs  # Unused by vikings.
          return spam + spam + spam
      
      358)

    Xin lưu ý không lạm dụng đặt tên một ký tự. Nói chung, tính mô tả phải tỷ lệ thuận với phạm vi hiển thị của tên. 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
    
    347 có thể là một tên hay cho khối mã 5 dòng nhưng trong nhiều phạm vi lồng nhau, nó có thể quá mơ hồ

  • dấu gạch ngang (

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    255) trong bất kỳ tên gói/mô-đun nào

  • def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    361 tên (dành riêng bởi Python)

  • điều khoản xúc phạm

  • những tên không cần thiết bao gồm loại biến (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
    
    362)

3. 16. 2 Quy ước đặt tên

  • “Nội bộ” có nghĩa là nội bộ của một mô-đun hoặc được bảo vệ hoặc riêng tư trong một lớp

  • Việc thêm trước một dấu gạch dưới (

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    28) có một số hỗ trợ để bảo vệ các biến và chức năng của mô-đun (linters sẽ gắn cờ quyền truy cập của thành viên được bảo vệ)

  • Việc thêm trước một dấu gạch dưới 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
    
    364 hay còn gọi là “dunder”) vào một biến thể hiện hoặc phương thức sẽ làm cho biến hoặc phương thức đó trở nên riêng tư đối với lớp của nó (sử dụng xáo trộn tên); . Thích một dấu gạch dưới

  • Đặt các lớp liên quan và các chức năng cấp cao nhất cùng nhau trong một mô-đun. Không giống như Java, không cần giới hạn bản thân trong một lớp cho mỗi mô-đun

  • Sử dụng CapWords cho tên lớp, nhưng Lower_with_under. py cho tên mô-đun. Mặc dù có một số mô-đun cũ có tên là CapWords. py, điều này hiện không được khuyến khích vì thật khó hiểu khi mô-đun được đặt tên theo một lớp. (“chờ đã – tôi đã viết

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

  • Dấu gạch dưới có thể xuất hiện trong các tên phương thức kém nhất bắt đầu bằng

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    367 để phân tách các thành phần logic của tên, ngay cả khi các thành phần đó sử dụng CapWords. Một mẫu có thể là
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    368; . Không có một cách chính xác nào để đặt tên cho các phương pháp thử nghiệm

3. 16. 3 Đặt tên tệp

Tên tệp Python phải có phần mở rộng là

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
267 và không được chứa dấu gạch ngang (
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
255). Điều này cho phép chúng được nhập và không được kiểm tra. Nếu bạn muốn có thể truy cập tệp thực thi mà không cần tiện ích mở rộng, hãy sử dụng liên kết tượng trưng hoặc trình bao bọc bash đơn giản có chứa
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
372

3. 16. 4 Nguyên tắc rút ra từ Khuyến nghị của Guido

TypePublicInternalPackages
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
373Modules
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
375Classes
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
376
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
377Exceptions
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
376Functions
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
379
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
380Global/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
381
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
382Global/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
373
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
375Instance Variables
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
375 (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
379
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
380 (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
373Local Variables
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
373

3. 16. 5 Ký hiệu toán học

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
391 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
225 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
393 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
394 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
395

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

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
01

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

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. Nếu một hàm vượt quá khoảng 40 dòng, hãy nghĩ xem có thể chia nhỏ hàm đó mà không làm hại cấu trúc của chương trình hay không

Ngay cả khi chức năng lâu dài của bạn hiện đang hoạt động hoàn hảo, ai đó sửa đổi nó sau vài tháng có thể thêm hành vi mới. Điều này có thể dẫn đến các lỗi khó tìm. Giữ chức năng của bạn ngắn gọn và đơn giản giúp người khác đọc và sửa đổi mã của bạn dễ dàng hơn

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

3. 19 Type Annotations

3. 19. 1 General Rules

  • Familiarize yourself with PEP-484

  • In methods, only annotate

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

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

  • 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
    
    399 (where
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98 is the only valid option)

  • Nếu bất kỳ biến nào khác hoặc kiểu trả về không được biểu thị, 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
    
    401

  • Bạn không bắt buộc phải chú thích tất cả các chức năng trong một mô-đun

    • Ít nhất hãy chú thích các API công khai của bạn
    • Sử dụng phán đoán để đạt được sự cân bằng tốt giữa một mặt là an toàn và rõ ràng, mặt khác là linh hoạt
    • Chú thích mã dễ bị lỗi liên quan đến loại (lỗi trước đó hoặc độ phức tạp)
    • Chú thích mã khó hiểu
    • Annotate code as it becomes stable from a types perspective. Trong nhiều trường hợp, bạn có thể chú thích tất cả các chức năng trong mã trưởng thành mà không mất quá nhiều tính linh hoạt

3. 19. Ngắt 2 dòng

Cố gắng tuân theo các quy tắc thụt đầu dòng hiện có

Sau khi chú thích, nhiều chữ ký hàm sẽ trở thành “mỗi dòng một tham số”. Để đảm bảo kiểu trả về cũng được cung cấp dòng riêng, có thể đặt dấu phẩy sau tham số 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
03

Always prefer breaking between variables, and not, for example, between variable names and type annotations. Tuy nhiên, nếu mọi thứ phù hợp trên cùng một dòng, hãy tiếp tục

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

Nếu tổ hợp tên hàm, tham số cuối cùng và kiểu trả về quá dài, hãy thụt lề 4 trong một dòng mới. Khi sử dụng ngắt dòng, hãy ưu tiên đặt từng tham số và kiểu trả về trên các dòng riêng của chúng và căn chỉnh dấu ngoặc đơn đó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
250

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

Tùy chọn, kiểu trả về có thể được đặt trên cùng một dòng với tham số 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
06

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
18 cho phép bạn di chuyển dấu ngoặc đơn đóng sang một dòng mới và căn chỉnh với dòng mở đầu, nhưng điều này khó đọc 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
07

Như trong các ví dụ trên, không muốn ngắt các loại. Tuy nhiên, đôi khi chúng quá dài để nằm trên một dòng (cố gắng giữ cho các loại phụ không bị gián đoạn)

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

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. Phương án cuối cùng là ngắt sau dấu hai chấm và thụt vào 4

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

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

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 tên lớp bên trong phần khai báo của lớp đó hoặc nếu bạn sử dụng một lớp được xác định sau trong mã –

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

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

3. 19. 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
251 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
13

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

3. 19. 5 Không có Loại

Trong hệ thống kiểu Python,

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
406 là kiểu "hạng nhất" và vì mục đích đá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
98 là bí danh 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
406. Nếu một đối số có thể là
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
98, thì nó phải được khai báo. Bạn có thể 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
410, nhưng nếu chỉ có một loại khác, 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
411

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
411 rõ ràng 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
411 ngầm định. Các phiên bản trước của PEP 484 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
414 được hiểu là
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
415, nhưng đó không còn là hành vi ưa thích nữa

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

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

3. 19. 6 bí danh loại

Bạn có thể khai báo bí danh của các loại phức tạp. Tên của bí danh phải là CapWorded. Nếu bí danh chỉ được sử dụng trong mô-đun này, thì bí danh đó phải là _Private

Ví dụ: nếu tên của mô-đun cùng với tên của loại quá dài

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

Các ví dụ khác là các kiểu lồng nhau phức tạp và nhiều biến trả về từ một hàm (dưới dạng một bộ)

3. 19. 7 kiểu phớt lờ

Bạn có thể tắt kiểm tra loại trên một dòng bằng nhận xét đặc 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
416

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
417 có tùy chọn tắt đối với các lỗi cụ thể (tương tự như lint)

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

3. 19. 8 biến gõ

Phép gán được chú thích Nếu một biến nội bộ có loại khó hoặc không thể suy luận, hãy chỉ định loại của biến đó bằng phép gán có chú thích - sử dụng dấu hai chấm và nhập giữa tên biến và giá trị (tương tự như được thực hiện với các đối số hàm có 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
19

Type CommentsThough you may see them remaining in the codebase (they were necessary before Python 3. 6), không thêm bất kỳ cách sử dụng nào nữa của 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
418 ở 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
00

3. 19. 9 Tuples vs Danh sách

Danh sách đã nhập chỉ có thể chứa các đối tượng thuộc một loại. Các bộ dữ liệu đã nhập có thể có một loại lặp lại duy nhất hoặc một số phần tử được đặt với các loại khác nhau. Cái sau thường được sử dụng làm kiểu trả về từ một hàm

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

3. 19. 10 LoạiVars

Hệ thống loại Python có thuốc generic. 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
355 là một cách phổ biến để sử dụng chúng

Thí dụ

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

Một TypeVar có thể bị ràng buộc

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

Biến loại được xác định trước phổ biến trong 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
321 là
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
421. Sử dụng nó cho nhiều chú thích có thể là
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
422 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
423 và tất cả phải cùng loại

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

TypeVar phải có tên mô tả, 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
  • không bị hạn chế

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

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

3. 19. 11 loại chuỗi

Khô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
424 trong mã mới. Nó chỉ tương thích với Python 2/3

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
423 cho dữ liệu chuỗi/văn bản. Đối với mã liên quan đến dữ liệu nhị phân, 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
422

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

Nếu tất cả các kiểu chuỗi của một hàm luôn giống nhau, chẳng hạn nếu kiểu trả về giống với kiểu đối số trong đoạn mã trên, hãy sử dụng AnyStr

3. 19. 12 Nhập khẩu để gõ

Đối với các ký hiệu 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
321 và
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
322 được sử dụng để hỗ trợ phân tích tĩnh và kiểm tra loại, hãy luôn nhập chính ký hiệu đó. Điều này giữ cho các chú thích phổ biến ngắn gọn hơn và phù hợp với các cách gõ được sử dụng trên khắp thế giới. Bạn rõ ràng được phép nhập nhiều lớp cụ thể trên một dòng 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
321 và
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
322. Bá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
08

Cho rằng cách nhập này sẽ thêm các mục vào không gian tên cục bộ, các tên trong

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
321 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
322 phải được xử lý tương tự như các từ khóa và không được xác định trong mã Python của bạn, được nhập hay không. 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
433

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

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

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

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

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

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

3. 19. 13 Conditional Imports

Use conditional imports only in exceptional cases where the additional imports needed for type checking must be avoided at runtime. Mô hình này không được khuyến khích;

Các mục nhập chỉ cần thiết cho chú thích loại có thể được đặt trong khối

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

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

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

3. 19. 14 phụ thuộc tuần hoàn

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

Thay thế các mô-đun tạo nhập khẩu phụ thuộc vòng tròn bằng

def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
401. Set an alias with a meaningful name, and use the real type name from this module (any attribute of Any is Any). Alias definitions should be separated from the last import by one line

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

3. 19. 15 thuốc gốc

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
401

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

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

If the best type parameter for a generic is

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

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

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

4 Parting Words

BE CONSISTENT

Nếu bạn đang chỉnh sửa mã, hãy dành vài phút để xem mã xung quanh bạn và xác định phong cách của nó. 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. If their comments have little boxes of hash marks around them, make your comments have little boxes of hash marks around them too

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