Python annotation specification

Posted by IceDragon on Thu, 11 Nov 2021 11:38:57 +0100

Note: the following is taken from , recorded here for reference

Document string

Python has a unique annotation method: using document strings. Document strings are the first statement in a package, module, class or function. These strings can be passed through the object__ doc__ Members are automatically extracted and used by pydoc. (you can run pydoc on your module to see what it looks like). Our convention for document strings is to use triple double quotation marks "" (PEP-257). A document string should be organized like this: first, a line of overview ending with a period, a question mark or an exclamation point (or the document string has only one line) . then an empty line. Then the rest of the document string, which should be aligned with the first quotation mark on the first line of the document string. There are more formatting specifications for the document string below


Each file should contain a license template. Select the appropriate template according to the license used by the project (for example, Apache 2.0, BSD, LGPL, GPL)

Functions and methods

The following functions include functions, methods, and generators

A function must have a document string unless it meets the following conditions:

External invisible
Very short
Simple and clear
The document string should contain a detailed description of what the function does and the input and output. Generally, it should not describe "how to do it" ", except for some complex algorithms. The document string should provide enough information. When someone writes code to call this function, he doesn't need to look at a line of code, just look at the document string. For complex code, adding comments next to the code will be more meaningful than using the document string

Several aspects of the function should be described and recorded in specific sections, as described below. Each section should start with a title line. The title line ends with a colon. In addition to the title line, other contents of the section should be indented by 2 spaces

List the name of each parameter, and use a colon and a space after the name to separate the description of the parameter. If the description is too long and exceeds 80 characters in a single line, use the hanging indentation of 2 or 4 spaces (consistent with other parts of the file). The description should include the required type and meaning. If a function accepts * foo (variable length parameter list) or * * bar * Foo and * * bar should be listed in detail

Returns: (or Yields: for generator)
Describes the type and semantics of the return value. If the function returns None, this part can be omitted

Lists all exceptions related to the interface

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.

        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For

        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}

        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.

        IOError: An error occurred accessing the bigtable.Table object.


Class should have a document string under its definition to describe the class. If your class has public attributes, there should be an attributes section in the document. And it should follow the same format as the function parameters

class SampleClass(object):
    """Summary of class here.

    Longer class information....
    Longer class information....

        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.

    def __init__(self, likes_spam=False):
        """Inits SampleClass with blah."""
        self.likes_spam = likes_spam
        self.eggs = 0

    def public_method(self):
        """Performs operation blah."""

Block and line comments

If you have to explain it in the next code review, you should write comments for it now. For complex operations, you should write several lines of comments before the operation begins. For code that is not clear at a glance, you should add comments at the end of the line

# We use a weighted dictionary search to find out where i is in
# the array.  We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.

if i & (i-1) == 0:        # true iff i is a power of 2

To improve readability, comments should be at least 2 spaces away from the code
On the other hand, never describe the code. Suppose the person reading the code knows Python better than you, he just doesn't know what your code is going to do

# BAD COMMENT: Now go through the b array and make sure whenever i occurs
# the next element is i+1

Topics: Python