Python gõ danh sách trống

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

Để giúp bạn định dạng mã chính xác, chúng tôi đã tạo tệp cài đặt cho Vim. 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 is a tool for finding bugs and style problems in Python source code. It finds problems that are typically caught by a compiler for less dynamic languages like C and C++. Because of the dynamic nature of Python, some warnings may be incorrect; however, spurious warnings should be fairly infrequent

2. 1. 2 Pros

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

2. 1. 3 Cons

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

2. 1. 4 Decision

Make sure you run

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

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

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

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

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

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

You can get a list of

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

To get more information on a particular message, use

Prefer

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

Unused argument warnings can be suppressed by deleting the variables at the beginning of the function. Always include a comment explaining why you are deleting it. “Unused. ” is sufficient. 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

Other common forms of suppressing this warning include using ‘

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

2. 2 Imports

Use

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

2. 2. 1 Definition

Reusability mechanism for sharing code from one module to another

2. 2. 2 Pros

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

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

2. 2. 3 Cons

Module names can still collide. 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)

For example the module

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

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

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

2. 2. 4. 1 Exemptions

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

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

2. 3 Packages

Import each module using the full pathname location of the module

2. 3. 1 Pros

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

2. 3. 2 Cons

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

2. 3. 3 Decision

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

Imports should be as follows

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

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

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

  _FOO = flags.DEFINE_string(...)

(assume this file lives in

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

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

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

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

2. 4 Exceptions

Exceptions are allowed but must be used carefully

2. 4. 1 Định nghĩa

Ngoại lệ là phương tiện thoát ra khỏi luồng điều khiển thông thường để xử lý lỗi hoặc các điều kiện ngoại lệ khác

2. 4. 2 Ưu điểm

Luồng điều khiển của mã hoạt động bình thường không bị lộn xộn bởi mã xử lý lỗi. Nó cũng cho phép luồng điều khiển bỏ qua nhiều khung khi một điều kiện nhất định xảy ra, e. g. , quay lại từ N hàm lồng nhau trong một bước thay vì phải tìm mã lỗi thông qua

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

Có thể khiến luồng điều khiển bị nhầm lẫn. Dễ bỏ sót các trường hợp lỗi khi gọi thư viện

2. 4. 4 Quyết định

Ngoại lệ phải tuân theo các điều kiện nhất định

  • Sử dụng các lớp ngoại lệ tích hợp khi nó hợp lý. Ví dụ: tăng

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    54 để chỉ ra lỗi lập trình như điều kiện tiên quyết bị vi phạm (chẳng hạn như nếu bạn được thông qua số âm nhưng yêu cầu số dương). Không 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
    
    55 để xác thực giá trị đối số của API công khai.
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    55 được sử dụng để đảm bảo tính đúng đắn bên trong, không phải để bắt buộc sử dụng đúng cách cũng như không chỉ ra rằng một số sự kiện bất ngờ đã xảy ra. Nếu một ngoại lệ được mong muốn trong các trường hợp sau, hãy sử dụng câu lệnh nâng cao. Ví dụ

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

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

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

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

  • 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

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

    Python is very tolerant in this regard and

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

  • Minimize the amount of code in a

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    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 block. The larger the body of the
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    63, the more likely that an exception will be raised by a line of code that you didn’t expect to raise an exception. 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 đồng thời với hai cơ sở dữ liệu khác nhau (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ạo nội bộ bằng cách thêm một _______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 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 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 bộ chứa và bộ lặp mà không cần sử dụng các vòng lặp truyền thống,

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

2. 7. 2 Ưu điểm

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2. 8. 1 Định nghĩa

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

2. 8. 2 Ưu điểm

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

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

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

2. 8. 4 Quyết định

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

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

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

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

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

2. 9. 1 Definition

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

2. 9. 2 Ưu điểm

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

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

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

2. 9. 4 Quyết định

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

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

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

2. 10 Hàm Lambda

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

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

2. 10. 1 Định nghĩa

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

2. 10. 2 Ưu điểm

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 mã đó là mã thông thường

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

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

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

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

2. 11. 1 Định nghĩa

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

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

2. 11. 2 Ưu điểm

Shorter and more convenient than an if statement

2. 11. 3 Cons

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

2. 11. 4 Quyết định

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

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

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

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

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

2. 12. 1 Định nghĩa

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

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

2. 12. 2 Ưu điểm

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

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

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

2. 12. 4 Quyết định

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

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

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

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

2. 13 thuộc tính

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

2. 13. 1 Định nghĩa

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

2. 13. 2 Ưu điểm

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

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

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

2. 13. 4 Quyết định

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

Ví dụ: không được phép sử dụng 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 (). Trong khi đó, việc sử dụng một thuộc tính để kiểm soát quyền truy cập thuộc tính hoặc để tính toán một giá trị có nguồn gốc tầm thường được cho phép. logic rất đơn giản và không có gì đáng ngạc nhiên

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

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

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

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

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

2. 14. 1 Định nghĩa

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

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

2. 14. 2 Ưu điểm

Các điều kiện sử dụng booleans Python dễ đọc hơn và ít bị lỗi hơn. In most cases, they’re also faster

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 Decision

Use the “implicit” false if possible, 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 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
95. There are a few caveats that you should keep in mind though

  • Always use

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    96 (or
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    97) to check 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
    
    98 value. E. g. , when testing whether a variable or argument that defaults to
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98 was set to some other value. The other value might be a value that’s false in a boolean context

  • Never compare a boolean variable to

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    92 using
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    01. Use
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    02 instead. If you need to distinguish
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    92 from
    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98 then chain the expressions, such as
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    05

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

    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    06 and
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    07 are preferable to
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    08 and
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    09 respectively

  • When handling integers, implicit false may involve more risk than benefit (i. e. , accidentally handling

    def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
        del beans, eggs  # Unused by vikings.
        return spam + spam + spam
    
    98 as 0). You may compare a value which is known to be an integer (and is not the result of
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    11) against the integer 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

  • Note that

    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    12 (i. e. ,
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    13 as string) evaluates to true

  • Note that Numpy arrays may raise an exception in an implicit boolean context. Prefer the

    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    14 attribute when testing emptiness of a
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    15 (e. g.
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    16)

2. 16 Lexical Scoping

Okay to use

2. 16. 1 Definition

A nested Python function can refer to variables defined in enclosing functions, but cannot assign to them. Variable bindings are resolved using lexical scoping, that is, based on the static program text. Any assignment to a name in a block will cause Python to treat all references to that name as a local variable, even if the use precedes the assignment. If a global declaration occurs, the name is treated as a global variable

An example of the use of this feature is

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 Pros

Often results in clearer, more elegant code. Especially comforting to experienced Lisp and Scheme (and Haskell and ML and …) programmers

2. 16. 3 Cons

Can lead to confusing bugs. Such as this example based on 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

So

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
17 will print
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
18, not
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
19

2. 16. 4 Decision

Okay to use

2. 17 Function and Method Decorators

Use decorators judiciously when there is a clear advantage. Avoid

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
20 and limit use of
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
21

2. 17. 1 Definition

(a. k. a “the

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
22 notation”). One common decorator is
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
91, used for converting ordinary methods into dynamically computed attributes. However, the decorator syntax allows for user-defined decorators as well. Specifically, for some function
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
24, this

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

is equivalent to

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

2. 17. 2 Pros

Elegantly specifies some transformation on a method; the transformation might eliminate some repetitive code, enforce invariants, etc

2. 17. 3 Cons

Decorators can perform arbitrary operations on a function’s arguments or return values, resulting in surprising implicit behavior. Additionally, decorators execute at object definition time. For module-level objects (classes, module functions, …) this happens at import time. Failures in decorator code are pretty much impossible to recover from

2. 17. 4 Decision

Use decorators judiciously when there is a clear advantage. Decorators should follow the same import and naming guidelines as functions. Decorator pydoc should clearly state that the function is a decorator. Write unit tests for decorators

Avoid external dependencies in the decorator itself (e. g. don’t rely on files, sockets, database connections, etc. ), since they might not be available when the decorator runs (at import time, perhaps from

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
25 or other tools). A decorator that is called with valid parameters should (as much as possible) be guaranteed to succeed in all cases

Decorators are a special case of “top level code” - see for more discussion

Never use

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
20 unless forced to in order to integrate with an API defined in an existing library. Write a module level function instead

Use

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
21 only when writing a named constructor, or a class-specific routine that modifies necessary global state such as a process-wide cache

2. 18 Threading

Do not rely on the atomicity of built-in types

While Python’s built-in data types such as dictionaries appear to have atomic operations, there are corner cases where they aren’t atomic (e. g. if

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
28 or
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
29 are implemented as Python methods) and their atomicity should not be relied upon. Neither should you rely on atomic variable assignment (since this in turn depends on dictionaries)

Use the Queue module’s

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
30 data type as the preferred way to communicate data between threads. Otherwise, use the threading module and its locking primitives. Prefer condition variables and
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
31 instead of using lower-level locks

2. 19 Power Features

Avoid these features

2. 19. 1 Definition

Python is an extremely flexible language and gives you many fancy features such as custom metaclasses, access to bytecode, on-the-fly compilation, dynamic inheritance, object reparenting, import hacks, reflection (e. g. some uses of

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
32), modification of system internals,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
33 methods implementing customized cleanup, etc

2. 19. 2 Pros

These are powerful language features. They can make your code more compact

2. 19. 3 Cons

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. It’s harder to read, understand, and debug code that’s using unusual features underneath. It doesn’t seem that way at first (to the original author), but when revisiting the code, it tends to be more difficult than code that is longer but is straightforward

2. 19. 4 Decision

Avoid these features in your code

Standard library modules and classes that internally use these features are okay to use (for example,

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

2. 20 Modern Python. từ __future__ nhập khẩu

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

2. 20. 1 Định nghĩa

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

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

2. 20. 2 Ưu điểm

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

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

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

2. 20. 4 Quyết định

từ __future__ nhập khẩu

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

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

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

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

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

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

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

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

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

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

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

2. 21. 1 Định nghĩa

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

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

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

2. 21. 2 Ưu điểm

Loại chú thích cải thiện khả năng đọc và bảo trì mã của bạn. The type checker will convert many runtime errors to build-time errors, and reduce your ability to use

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

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

2. 21. 4 Quyết định

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

3 quy tắc kiểu Python

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
45,
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
46 hoặc
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
47 không xuất hiện trên cùng một dòng với phần tử cuối cùng. Sự hiện diện của dấu phẩy ở cuối cũng được sử dụng như một gợi ý cho trình định dạng tự động mã 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ó _
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
48 sau phần tử cuối cùng

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

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

3. 5 dòng trống

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

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

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

3. 6 Khoảng trắng

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

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

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

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

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

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

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

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

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

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

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

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

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

  _FOO = flags.DEFINE_string(...)
0

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

  _FOO = flags.DEFINE_string(...)
1

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

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

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

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

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

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

  _FOO = flags.DEFINE_string(...)
2

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

  _FOO = flags.DEFINE_string(...)
3

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

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

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

  _FOO = flags.DEFINE_string(...)
4

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

  _FOO = flags.DEFINE_string(...)
5

3. 7 dòng Shebang

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

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

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

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

3. 8. 1 tài liệu

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

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

3. 8. 2 mô-đun

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

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

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

  _FOO = flags.DEFINE_string(...)
6

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

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

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

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

  _FOO = flags.DEFINE_string(...)
7

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

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

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

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

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

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

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

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

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

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

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

Liệt kê từng tham số theo tên. Mô tả phải theo sau tên và được phân tách bằng dấu hai chấm, sau đó là khoảng trắng hoặc xuống dòng. Nếu mô tả quá dài để vừa với một dòng 80 ký tự, hãy sử dụng thụt lề treo nhiều hơn 2 hoặc 4 khoảng trắng so với tên tham số (nhất quán với phần còn lại của chuỗi tài liệu trong tệp). Mô tả phải bao gồm (các) loại bắt buộc nếu mã không chứa chú thích loại tương ứng. Nếu một hàm chấp nhận
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
81 (danh sách đối số có độ dài thay đổi) và/hoặc
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
82 (đối số từ khóa tùy ý), thì chúng phải được liệt kê là
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
81 và
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
82. Mô tả loại và ngữ nghĩa của giá trị trả về. Nếu hàm chỉ trả về Không thì không cần phần này. Nó cũng có thể được bỏ qua nếu chuỗi tài liệu bắt đầu bằng Returns hoặc Yields (e. g.
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
85) và câu mở đầu đủ để mô tả giá trị trả về. Không bắt chước 'kiểu NumPy' (ví dụ), kiểu này thường ghi lại giá trị trả về của bộ dữ liệu như thể đó là nhiều giá trị trả về với các tên riêng lẻ (không bao giờ đề cập đến bộ dữ liệu). Thay vào đó, hãy mô tả một giá trị trả về như. “Trả về. Một bộ (mat_a, mat_b), trong đó mat_a là …, và…”. Các tên phụ trợ trong chuỗi tài liệu không nhất thiết phải tương ứng với bất kỳ tên nội bộ nào được sử dụng trong thân hàm (vì chúng không phải là một phần của API). Liệt kê tất cả các ngoại lệ có liên quan đến giao diện theo sau là mô tả. Sử dụng tên ngoại lệ tương tự + dấu hai chấm + dấu cách hoặc dòng mới và kiểu thụt lề treo như được mô tả trong Args. Bạn không nên ghi lại các trường hợp ngoại lệ được nêu ra nếu API được chỉ định trong chuỗi tài liệu bị vi phạm (vì điều này nghịch lý sẽ tạo ra hành vi vi phạm phần API của API)

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

  _FOO = flags.DEFINE_string(...)
8

Similarly, this variation on

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

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

  _FOO = flags.DEFINE_string(...)
9

3. 8. 4 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

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
87 và tuân theo cùng định dạng như phần

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

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ả nội dung của ngoại lệ chứ không phải bối cảnh mà ngoại lệ đó 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

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

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

3. 8. 5 Khối và Nhận xét Nội tuyến

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

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

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

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
65, theo sau là ít nhất một khoảng trắng trước văn bản của chính nhận xét đó

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

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

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

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

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

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

3. 10 Dây

Sử dụng toán tử ,

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
59 hoặc phương pháp
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
92 để định dạng chuỗi, ngay cả khi các tham số đều là chuỗi. Sử dụng phán đoán tốt nhất của bạn để quyết định giữa các tùy chọn định dạng chuỗi. Một liên kết duy nhất với
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
54 thì được nhưng không định dạng với
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
54

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

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

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

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
54 và
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
96 để tích lũy một chuỗi trong một vòng lặp. Trong một số điều kiện, tích lũy một chuỗi với phép cộng có thể dẫn đến thời gian chạy bậc hai thay vì tuyến tính. Mặc dù các tích lũy phổ biến thuộc loại này có thể được tối ưu hóa trên CPython, nhưng đó là chi tiết triển khai. Các điều kiện áp dụng tối ưu hóa không dễ dự đoán và có thể thay đổi. Thay vào đó, hãy thêm từng chuỗi con vào danh sách và
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
97 danh sách sau khi vòng lặp kết thúc hoặc ghi từng chuỗi con vào bộ đệm
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
98. Các kỹ thuật này luôn có độ phức tạp thời gian chạy tuyến tính được khấu hao

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

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

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

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

  _FOO = absl.flags.DEFINE_string(...)
00 và gắn bó với nó. Bạn có thể sử dụng ký tự trích dẫn khác trên một chuỗi để tránh phải ký tự trích dẫn thoát dấu gạch chéo ngược trong chuỗi

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

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

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

    Returns:
      The new minimum port.

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

Thích

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
74 cho các chuỗi nhiều dòng hơn là
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
02. Các dự án có thể chọn sử dụng
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
02 cho tất cả các chuỗi nhiều dòng không phải chuỗi doc nếu và chỉ khi chúng cũng sử dụng
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
99 cho các chuỗi thông thường. Docstrings phải sử dụng
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
74 bất kể

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

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

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

    Returns:
      The new minimum port.

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

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

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

    Returns:
      The new minimum port.

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

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

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

    Returns:
      The new minimum port.

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

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

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

    Returns:
      The new minimum port.

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

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

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

    Returns:
      The new minimum port.

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

3. 10. 1 nhật ký

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

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

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

    Returns:
      The new minimum port.

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

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

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

    Returns:
      The new minimum port.

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

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

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

    Returns:
      The new minimum port.

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

3. 10. 2 Error Messages

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

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

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

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

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

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

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

    Returns:
      The new minimum port.

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

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

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

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

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

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

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

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

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

  • Không có gì đảm bảo khi nào bộ thực thi sẽ thực sự gọi phương thức
    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    33. Các triển khai Python khác nhau sử dụng các kỹ thuật quản lý bộ nhớ khác nhau, chẳng hạn như bộ sưu tập rác bị trì hoãn, điều này có thể làm tăng tuổi thọ của đối tượng một cách tùy ý và vô thời hạn
  • Các tham chiếu không mong muốn đến tệp, e. g. trong toàn cầu hoặc theo dõi ngoại lệ, có thể giữ nó lâu hơn dự định

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

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

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

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

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

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

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
42, hãy sử dụng
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

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

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

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

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

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

Sử dụng

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

  _FOO = absl.flags.DEFINE_string(...)
12 nhận xét cho mã tạm thời, giải pháp ngắn hạn hoặc đủ tốt nhưng không hoàn hảo

Một nhận xét

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

  _FOO = absl.flags.DEFINE_string(...)
12 bắt đầu bằng từ
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 viết hoa toàn bộ và một mã định danh ngữ cảnh được đặt trong ngoặc đơn. Lý tưởng nhất là tham chiếu lỗi, đôi khi là tên người dùng. Một tài liệu tham khảo lỗi như
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
15 là thích hợp hơn, bởi vì các lỗi được theo dõi và có các nhận xét tiếp theo, trong khi các cá nhân di chuyển xung quanh và có thể mất ngữ cảnh theo thời gian.
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 được theo sau bởi một lời giải thích về những việc phải làm

Mục đích là để có một định dạng

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

  _FOO = absl.flags.DEFINE_string(...)
12 nhất quán có thể được tìm kiếm để tìm hiểu cách biết thêm chi tiết.
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 không phải là cam kết rằng người được giới thiệu sẽ khắc phục vấn đề. Do đó, khi bạn tạo một
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
12 với tên người dùng, thì hầu như tên người dùng của bạn luôn được cung cấp

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

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

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

Nếu

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

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

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

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

E. g

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

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

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

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

  1. Báo cáo nhập khẩu trong tương lai của Python. Ví dụ

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

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

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

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

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

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

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

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

    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 từng mô-đun (_______33_______23 trong ____33_______24). Mã có thể tùy chọn đặt một dòng trống giữa các phần nhập

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

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

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

3. 14 Tuyên bố

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ì
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 không thể vừa trên cùng một dòng và bạn chỉ có thể làm như vậy với
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
29 nếu không có
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

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

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

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

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

3. 15 Getters và Setters

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

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

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. The function invocation hints that a potentially non-trivial operation is occurring. Ngoài ra, có thể là một tùy chọn khi cần logic đơn giản hoặc tái cấu trúc để không còn cần getters và setters nữa

Getters và setters nên tuân theo các nguyên tắc, chẳng hạn như

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
67. 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.
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      47,
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      48,
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      49,
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      50, v.v. )
    • Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      51 làm định danh ngoại lệ trong câu lệnh
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      52
    • Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      53 dưới dạng xử lý tệp trong câu lệnh
      from sound.effects import echo
      ...
      echo.EchoFilter(input, output, delay=0.7, atten=4)
      
      42
    • riêng tư không có ràng buộc (e. g.
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      56,
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      57,
      Yes:
        # Reference absl.flags in code with the complete name (verbose).
        import absl.flags
        from doctor.who import jodie
      
        _FOO = absl.flags.DEFINE_string(...)
      
      58)

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

    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    47 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 (

    from sound.effects import echo
    ...
    echo.EchoFilter(input, output, delay=0.7, atten=4)
    
    55) trong bất kỳ tên gói/mô-đun nào

  • Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    61 tên (được đặt trước 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ụ:.

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

3. 16. 2 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

  • Đặt 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 (

    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    64 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ó một cách hiệu quả (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

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

  • 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

    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    67 để 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à
    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    68; . 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

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
67 và không được chứa dấu gạch ngang (
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
55). Điều này cho phép chúng được nhập và kiểm tra. Nếu bạn muốn một tệp thực thi có thể truy cập được 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
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Đối với mã nặng về mặt toán học, các tên biến ngắn sẽ vi phạm hướng dẫn kiểu được ưu tiên hơn khi chúng khớp với ký hiệu đã thiết lập trong tài liệu tham khảo hoặc thuật toán. Khi làm như vậy, hãy tham khảo nguồn của tất cả các quy ước đặt tên trong một nhận xét hoặc chuỗi tài liệu hoặc, nếu nguồn không thể truy cập được, hãy ghi lại rõ ràng các quy ước đặt tên. Ưu tiên

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

  _FOO = absl.flags.DEFINE_string(...)
91 tuân thủ PEP8 cho các API công khai, có nhiều khả năng gặp phải ngoài ngữ cảnh hơn

3. 17 chính

Trong Python,

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
25 cũng như các bài kiểm tra đơn vị yêu cầu các mô-đun có thể nhập được. Nếu một tệp được dùng làm tệp thực thi, thì chức năng chính của nó phải ở hàm
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
93 và mã của bạn phải luôn kiểm tra
Yes:
  # Reference absl.flags in code with the complete name (verbose).
  import absl.flags
  from doctor.who import jodie

  _FOO = absl.flags.DEFINE_string(...)
94 trước khi thực thi chương trình chính của bạn, để nó không được thực thi khi mô-đun được nhập

Khi sử dụng absl, hãy sử dụng

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

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

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

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

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

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

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

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

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

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

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

Nếu không, hãy sử dụng

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

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

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

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

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

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

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

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

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

Tất cả mã ở cấp cao nhất sẽ được thực thi khi mô-đun được nhập. Cẩn thận không gọi hàm, tạo đối tượng hoặc thực hiện các thao tác khác không được thực hiện khi tệp đang được ____32_______25ed

3. 18 Chiều dài chức năng

Thích các chức năng nhỏ và tập trung

Chúng tôi nhận ra rằng các hàm dài đôi khi phù hợp, vì vậy không có giới hạn cứng nào được đặt cho độ dài của hàm. 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

Bạn có thể tìm thấy các hàm dài và phức tạp khi làm việc với một số mã. Đừng bị đe dọa bằng cách sửa đổi mã hiện có. nếu làm việc với một chức năng như vậy tỏ ra khó khăn, bạn thấy rằng các lỗi khó gỡ lỗi hoặc bạn muốn sử dụng một phần của nó trong nhiều ngữ cảnh khác nhau, hãy cân nhắc chia chức năng thành các phần nhỏ hơn và dễ quản lý hơn

3. 19 Chú thích Loại

3. 19. 1 Quy tắc chung

  • Familiarize yourself with PEP-484

  • Trong các phương thức, chỉ chú 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
    
    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 nếu cần thiết cho thông tin loại phù hợp. e. g. ,

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

  • Tương tự, đừng cảm thấy bắt buộc phải chú thích giá trị trả về của

    Yes:
      # Reference absl.flags in code with the complete name (verbose).
      import absl.flags
      from doctor.who import jodie
    
      _FOO = absl.flags.DEFINE_string(...)
    
    99 (trong đó
    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à tùy chọn hợp lệ duy nhất)

  • Nếu không thể biểu thị bất kỳ biến nào khác hoặc kiểu trả về, hãy sử dụng

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

  • 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
    • Chú thích mã khi nó trở nên ổn định từ góc độ loại. 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 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

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

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

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

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

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

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

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

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

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

Luôn ưu tiên ngắt giữa các biến và không, ví dụ, giữa tên biến và chú thích loại. 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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)

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

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

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

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

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

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

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

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

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

Nếu một tên và loại quá dài, hãy xem xét sử dụng một loại cho. Phương án cuối cùng là ngắt sau dấu hai chấm và thụt vào 4

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
51 cho các đối số có cả chú thích loại và giá trị mặc định

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

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

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

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

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

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

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

Trong hệ thống kiểu Python,

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

  _FOO = flags.DEFINE_string(...)
06 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
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
06. If an argument can be
def viking_cafe_order(spam: str, beans: str, eggs: Optional[str] = None) -> str:
    del beans, eggs  # Unused by vikings.
    return spam + spam + spam
98, it has to be declared. Bạn có thể sử dụng
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
10, nhưng nếu chỉ có một loại khác, hãy sử dụng
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
11

Sử dụng

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

  _FOO = flags.DEFINE_string(...)
11 rõ ràng thay vì ngầm ẩn
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
11. Các phiên bản trước của PEP 484 cho phép
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
14 được hiểu là
Yes:
  # Reference flags in code with just the module name (common).
  from absl import flags
  from doctor.who import jodie

  _FOO = flags.DEFINE_string(...)
15, nhưng đó không còn là hành vi được ưu tiên nữa

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

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

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

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

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

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

3. 19. 6 Type Aliases

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

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

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

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

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

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

3. 19. 7 Ignoring Types

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

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

  _FOO = flags.DEFINE_string(...)
16

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

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

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

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

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

3. 19. 8 Typing Variables

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

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

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

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

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

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

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

3. 19. 9 Tuples vs Lists

Typed lists can only contain objects of a single type. Typed tuples can either have a single repeated type or a set number of elements with different types. The latter is commonly used as the return type from a function

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

3. 19. 10 TypeVars

The Python type system has . The factory function

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

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

Example

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

A TypeVar can be constrained

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

A common predefined type variable in the

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

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

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

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

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

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

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

  • not externally visible
  • not constrained

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

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

3. 19. 11 String types

Do not use

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

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

Use

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

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

  _FOO = flags.DEFINE_string(...)
22

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

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

3. 19. 12 Imports For Typing

For symbols from the

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

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

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

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

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

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

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

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

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

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

  _FOO = flags.DEFINE_string(...)
33

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

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

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

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

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

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

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

3. 19. 13 Conditional Imports

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

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

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

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

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

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

3. 19. 14 Circular Dependencies

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

Replace modules that create circular dependency imports with

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

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

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

3. 19. 15 Generics

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

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

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

If the best type parameter for a generic is

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

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

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

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

4 Parting Words

BE CONSISTENT

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

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