Python is the main dynamic language used at Google. This style guide is a list of dos and don’ts for Python programs
To help you format code correctly, we’ve created a settings file for Vim. For Emacs, the default settings should be fine
Many teams use the yapf auto-formatter to avoid arguing over formatting
2 Python Language Rules
2. 1 Lint
Run
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
18 over your code using this pylintrc2. 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 infrequent2. 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 it2. 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 codeSuppress 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
24If 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 doingTo 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
27Unused argument warnings can be suppressed by deleting the variables at the beginning of the function. Always include a comment explaining why you are deleting it. “Unused. ” is sufficient. For example
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
Other common forms of suppressing this warning include using ‘
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
28’ as the identifier for the unused argument or prefixing the argument name with ‘def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
29’, or assigning them to ‘def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
28’. These forms are allowed but no longer encouraged. These break callers that pass arguments by name and do not enforce that the arguments are actually unused2. 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 functions2. 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
342. 2. 3 Cons
Module names can still collide. Some module names are inconveniently long
2. 2. 4 Decision
- Use
35 for importing packages and modulesdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
- Use
36 wheredef 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 anddef 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 prefixdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
- Use
39 if two modules nameddef 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, ifdef 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 ifdef 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 namedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
- Use
43 only whendef 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 fordef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
46]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
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 followsdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
2Do 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 ExemptionsExemptions from this rule
- Symbols from the following modules are used to support static analysis and type checking
- Redirects from the six. moves module
2. 3 Packages
Import each module using the full pathname location of the module
2. 3. 1 Pros
Avoids conflicts in module names or incorrect imports due to the module search path not being what the author expected. Makes it easier to find modules
2. 3. 2 Cons
Makes it harder to deploy code because you have to replicate the package hierarchy. Not really a problem with modern deployment mechanisms
2. 3. 3 Decision
All new code should import each module by its full package name
Imports should be as follows
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
3def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
4[assume this file lives in
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
48 where def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
49 also exists]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
7The 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
492. 4 Exceptions
Exceptions are allowed but must be used carefully
2. 4. 1 Definition
Exceptions are a means of breaking out of normal control flow to handle errors or other exceptional conditions
2. 4. 2 Pros
The control flow of normal operation code is not cluttered by error-handling code. It also allows the control flow to skip multiple frames when a certain condition occurs, e. g. , returning from N nested functions in one step instead of having to plumb error codes through
2. 4. 3 Cons
May cause the control flow to be confusing. Easy to miss error cases when making library calls
2. 4. 4 Decision
Exceptions must follow certain conditions
Make use of built-in exception classes when it makes sense. For example, raise a
54 to indicate a programming mistake like a violated precondition [such as if you were passed a negative number but required a positive one]. Do not usedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
55 statements for validating argument values of a public API.def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
55 is used to ensure internal correctness, not to enforce correct usage nor to indicate that some unexpected event occurred. If an exception is desired in the latter cases, use a raise statement. For exampledef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
5dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
6dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
Libraries or packages may define their own exceptions. When doing so they must inherit from an existing exception class. Exception names should end in
57 and should not introduce repetition [def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
58]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Never use catch-all
59 statements, or catchdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
60 ordef 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 aredef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
- 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
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 catchdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Minimize the amount of code in a
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 thedef 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. In those cases, thedef 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 hides a real errordef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Use the
68 clause to execute code whether or not an exception is raised in thedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
63 block. This is often useful for cleanup, i. e. , closing a filedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
2. 5 Mutable Global State
Avoid mutable global state
2. 5. 1 Definition
Module level values or class attributes that can get mutated during program execution
2. 5. 2 Pros
Occasionally useful
2. 5. 3 Cons
Breaks encapsulation. Such design can make it hard to achieve valid objectives. For example, if global state is used to manage a database connection, then connecting to two different databases at the same time [such as for computing differences during a migration] becomes difficult. Similar problems easily arise with global registries
Has the potential to change module behavior during the import, because assignments to global variables are done when the module is first imported
2. 5. 4 Decision
Avoid mutable global state
In those rare cases where using global state is warranted, mutable global entities should be declared at the module level or as a class attribute and made internal by prepending an
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
28 to the name. If necessary, external access to mutable global state must be done through public functions or class methods. See Naming below. Please explain the design reasons why mutable global state is being used in a comment or a doc linked to from a commentModule-level constants are permitted and encouraged. For example.
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
71 for an internal use constant or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
72 for a public API constant. Constants must be named using all caps with underscores. See Naming below2. 6 Nested/Local/Inner Classes and Functions
Nested local functions or classes are fine when used to close over a local variable. Inner classes are fine
2. 6. 1 Definition
A class can be defined inside of a method, function, or class. A function can be defined inside a method or function. Nested functions have read-only access to variables defined in enclosing scopes
2. 6. 2 Pros
Allows definition of utility classes and functions that are only used inside of a very limited scope. Very ADT-y. Commonly used for implementing decorators
2. 6. 3 Cons
Nested functions and classes cannot be directly tested. Nesting can make the outer function longer and less readable
2. 6. 4 Decision
They are fine with some caveats. Avoid nested functions or classes except when closing over a local value other than
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
73 or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
74. Do not nest a function just to hide it from users of a module. Instead, prefix its name with an _ at the module level so that it can still be accessed by tests2. 7 Comprehensions & Generator Expressions
Okay to use for simple cases
2. 7. 1 Definition
List, Dict, and Set comprehensions as well as generator expressions provide a concise and efficient way to create container types and iterators without resorting to the use of traditional loops,
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, or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
772. 7. 2 Pros
Simple comprehensions can be clearer and simpler than other dict, list, or set creation techniques. Generator expressions can be very efficient, since they avoid the creation of a list entirely
2. 7. 3 Cons
Complicated comprehensions or generator expressions can be hard to read
2. 7. 4 Decision
Okay to use for simple cases. Each portion must fit on one line. mapping expression,
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
78 clause, filter expression. Multiple def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
78 clauses or filter expressions are not permitted. Use loops instead when things get more complicateddef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
0def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
12. 8 Default Iterators and Operators
Use default iterators and operators for types that support them, like lists, dictionaries, and files
2. 8. 1 Definition
Container types, like dictionaries and lists, define default iterators and membership test operators [“in” and “not in”]
2. 8. 2 Pros
The default iterators and operators are simple and efficient. They express the operation directly, without extra method calls. A function that uses default operators is generic. It can be used with any type that supports the operation
2. 8. 3 Cons
You can’t tell the type of objects by reading the method names [unless the variable has type annotations]. This is also an advantage
2. 8. 4 Decision
Use default iterators and operators for types that support them, like lists, dictionaries, and files. The built-in types define iterator methods, too. Prefer these methods to methods that return lists, except that you should not mutate a container while iterating over it
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
0def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
12. 9 Generators
Use generators as needed
2. 9. 1 Definition
A generator function returns an iterator that yields a value each time it executes a yield statement. After it yields a value, the runtime state of the generator function is suspended until the next value is needed
2. 9. 2 Pros
Simpler code, because the state of local variables and control flow are preserved for each call. A generator uses less memory than a function that creates an entire list of values at once
2. 9. 3 Cons
Local variables in the generator will not be garbage collected until the generator is either consumed to exhaustion or itself garbage collected
2. 9. 4 Decision
Fine. Use “Yields. ” rather than “Returns. ” in the docstring for generator functions
If the generator manages an expensive resource, make sure to force the clean up
A good way to do the clean up is by wrapping the generator with a context manager PEP-0533
2. 10 Lambda Functions
Okay for one-liners. Prefer generator expressions over
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
75 or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
76 with a def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
772. 10. 1 Definition
Lambdas define anonymous functions in an expression, as opposed to a statement
2. 10. 2 Pros
Convenient
2. 10. 3 Cons
Harder to read and debug than local functions. The lack of names means stack traces are more difficult to understand. Expressiveness is limited because the function may only contain an expression
2. 10. 4 Decision
Okay to use them for one-liners. If the code inside the lambda function is longer than 60-80 chars, it’s probably better to define it as a regular nested function
For common operations like multiplication, use the functions from the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
83 module instead of lambda functions. For example, prefer def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
84 to def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
852. 11 Conditional Expressions
Okay for simple cases
2. 11. 1 Definition
Conditional expressions [sometimes called a “ternary operator”] are mechanisms that provide a shorter syntax for if statements. For example.
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
862. 11. 2 Pros
Shorter and more convenient than an if statement
2. 11. 3 Cons
May be harder to read than an if statement. The condition may be difficult to locate if the expression is long
2. 11. 4 Decision
Okay to use for simple cases. Each portion must fit on one line. true-expression, if-expression, else-expression. Use a complete if statement when things get more complicated
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
2def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
32. 12 Default Argument Values
Okay in most cases
2. 12. 1 Definition
You can specify values for variables at the end of a function’s parameter list, 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
87. If def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
88 is called with only one argument, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
89 is set to 0. If it is called with two arguments, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
89 has the value of the second argument2. 12. 2 Pros
Often you have a function that uses lots of default values, but on rare occasions you want to override the defaults. Default argument values provide an easy way to do this, without having to define lots of functions for the rare exceptions. As Python does not support overloaded methods/functions, default arguments are an easy way of “faking” the overloading behavior
2. 12. 3 Cons
Default arguments are evaluated once at module load time. This may cause problems if the argument is a mutable object such as a list or a dictionary. If the function modifies the object [e. g. , by appending an item to a list], the default value is modified
2. 12. 4 Decision
Okay to use with the following caveat
Do not use mutable objects as default values in the function or method definition
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
4def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
52. 13 Properties
Properties may be used to control getting or setting attributes that require trivial computations or logic. Property implementations must match the general expectations of regular attribute access. that they are cheap, straightforward, and unsurprising
2. 13. 1 Definition
A way to wrap method calls for getting and setting an attribute as a standard attribute access
2. 13. 2 Pros
- Allows for an attribute access and assignment API rather than getter and setter method calls
- Can be used to make an attribute read-only
- Allows calculations to be lazy
- Provides a way to maintain the public interface of a class when the internals evolve independently of class users
2. 13. 3 Cons
- Can hide side-effects much like operator overloading
- Can be confusing for subclasses
2. 13. 4 Decision
Properties are allowed, but, like operator overloading, should only be used when necessary and match the expectations of typical attribute access; follow the getters and setters rules otherwise
For example, using a property to simply both get and set an internal attribute isn’t allowed. there is no computation occurring, so the property is unnecessary [make the attribute public instead]. In comparison, using a property to control attribute access or to calculate a trivially derived value is allowed. the logic is simple and unsurprising
Properties should be created with the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
91 decorator. Manually implementing a property descriptor is considered a power featureInheritance with properties can be non-obvious. Do not use properties to implement computations a subclass may ever want to override and extend
2. 14 True/False Evaluations
Use the “implicit” false if at all possible
2. 14. 1 Definition
Python evaluates certain values as
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
92 when in a boolean context. A quick “rule of thumb” is that all “empty” values are considered false, so def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
93 all evaluate as false in a boolean context2. 14. 2 Pros
Conditions using Python booleans are easier to read and less error-prone. In most cases, they’re also faster
2. 14. 3 Cons
May look strange to C/C++ developers
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 thoughAlways use
96 [ordef 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 adef 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 todef 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 contextdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Never compare a boolean variable to
92 usingdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
201. Usedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
202 instead. If you need to distinguishdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
92 fromdef 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 asdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
205def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
For sequences [strings, lists, tuples], use the fact that empty sequences are false, so
206 anddef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
207 are preferable todef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
208 anddef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
209 respectivelydef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
When handling integers, implicit false may involve more risk than benefit [i. e. , accidentally handling
98 as 0]. You may compare a value which is known to be an integer [and is not the result ofdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
211] against the integer 0def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
6def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
7def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Note that
212 [i. e. ,def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
213 as string] evaluates to truedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Note that Numpy arrays may raise an exception in an implicit boolean context. Prefer the
214 attribute when testing emptiness of adef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
215 [e. g.def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
216]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
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
82. 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
9So
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
217 will print def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
218, not def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
2192. 16. 4 Decision
Okay to use
2. 17 Function and Method Decorators
Use decorators judiciously when there is a clear advantage. Avoid
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
220 and limit use of def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
2212. 17. 1 Definition
Decorators for Functions and Methods [a. k. a “the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
222 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 def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
224, thisdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
20is equivalent to
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
212. 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
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
225 or other tools]. A decorator that is called with valid parameters should [as much as possible] be guaranteed to succeed in all casesDecorators are a special case of “top level code” - see main for more discussion
Never use
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
220 unless forced to in order to integrate with an API defined in an existing library. Write a module level function insteadUse
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
221 only when writing a named constructor, or a class-specific routine that modifies necessary global state such as a process-wide cache2. 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
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
228 or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
229 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
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
230 data type as the preferred way to communicate data between threads. Otherwise, use the threading module and its locking primitives. Prefer condition variables and def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
231 instead of using lower-level locks2. 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
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
232], modification of system internals, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
233 methods implementing customized cleanup, etc2. 19. 2 Pros
These are powerful language features. They can make your code more compact
2. 19. 3 Cons
It’s very tempting to use these “cool” features when they’re not absolutely necessary. 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,
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
234, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
235, and def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
236]2. 20 Modern Python. from __future__ imports
New language version semantic changes may be gated behind a special future import to enable them on a per-file basis within earlier runtimes
2. 20. 1 Definition
Being able to turn on some of the more modern features via
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
237 statements allows early use of features from expected future Python versions2. 20. 2 Pros
This has proven to make runtime version upgrades smoother as changes can be made on a per-file basis while declaring compatibility and preventing regressions within those files. Modern code is more maintainable as it is less likely to accumulate technical debt that will be problematic during future runtime upgrades
2. 20. 3 Cons
Such code may not work on very old interpreter versions prior to the introduction of the needed future statement. The need for this is more common in projects supporting an extremely wide variety of environments
2. 20. 4 Decision
from __future__ importsUse of
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
237 statements is encouraged. It allows a given source file to start using more modern Python syntax features today. Once you no longer need to run on a version where the features are hidden behind a def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
239 import, feel free to remove those linesIn code that may execute on versions as old as 3. 5 rather than >= 3. 7, import
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
22For more information read the Python future statement definitions documentation
Please don’t remove these imports until you are confident the code is only ever used in a sufficiently modern environment. Even if you do not currently use the feature a specific future import enables in your code today, keeping it in place in the file prevents later modifications of the code from inadvertently depending on the older behavior
Use other
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
240 import statements as you see fit2. 21 Type Annotated Code
You can annotate Python code with type hints according to PEP-484, and type-check the code at build time with a type checking tool like pytype
Type annotations can be in the source or in a stub pyi file. Whenever possible, annotations should be in the source. Use pyi files for third-party or extension modules
2. 21. 1 Definition
Type annotations [or “type hints”] are for function or method arguments and return values
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
23You can also declare the type of a variable using similar PEP-526 syntax
2. 21. 2 Pros
Type annotations improve the readability and maintainability of your code. The type checker will convert many runtime errors to build-time errors, and reduce your ability to use Power Features
2. 21. 3 Cons
You will have to keep the type declarations up to date. You might see type errors that you think are valid code. Use of a type checker may reduce your ability to use Power Features
2. 21. 4 Decision
You are strongly encouraged to enable Python type analysis when updating code. When adding or modifying public APIs, include type annotations and enable checking via pytype in the build system. As static analysis is relatively new to Python, we acknowledge that undesired side-effects [such as wrongly inferred types] may prevent adoption by some projects. In those situations, authors are encouraged to add a comment with a TODO or link to a bug describing the issue[s] currently preventing type annotation adoption in the BUILD file or in the code itself as appropriate
3 Python Style Rules
3. 1 Semicolons
Do not terminate your lines with semicolons, and do not use semicolons to put two statements on the same line
3. 2 Line length
Maximum line length is 80 characters
Explicit exceptions to the 80 character limit
- Long import statements
- URLs, pathnames, or long flags in comments
- Long string module level constants not containing whitespace that would be inconvenient to split across lines such as URLs or pathnames
- Pylint disable comments. [e. g.
241]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
- Pylint disable comments. [e. g.
Do not use backslash line continuation except for
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
242 statements requiring three or more context managersMake use of Python’s implicit line joining inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
24When a literal string won’t fit on a single line, use parentheses for implicit line joining
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
25Within comments, put long URLs on their own line if necessary
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
26def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
27It is permissible to use backslash continuation when defining a
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
242 statement with three or more context managers. For two context managers, use a nested def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
242 statementdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
28def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
29def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
30Make note of the indentation of the elements in the line continuation examples above; see the indentation section for explanation
In all other cases where a line exceeds 80 characters, and the yapf auto-formatter does not help bring the line below the limit, the line is allowed to exceed this maximum. Authors are encouraged to manually break the line up per the notes above when it is sensible
3. 3 Parentheses
Use parentheses sparingly
It is fine, though not required, to use parentheses around tuples. Do not use them in return statements or conditional statements unless using parentheses for implied line continuation or to indicate a tuple
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
31def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
323. 4 Indentation
Indent your code blocks with 4 spaces
Never use tabs. Implied line continuation should align wrapped elements vertically [see line length examples], or use a hanging 4-space indent. Closing [round, square or curly] brackets can be placed at the end of the expression, or on separate lines, but then should be indented the same as the line with the corresponding opening bracket
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
33def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
343. 4. 1 Trailing commas in sequences of items?
Trailing commas in sequences of items are recommended only when the closing container token
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
245, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
246, or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
247 does not appear on the same line as the final element. The presence of a trailing comma is also used as a hint to our Python code auto-formatter YAPF to direct it to auto-format the container of items to one item per line when the def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
248 after the final element is presentdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
353. 5 Blank Lines
Two blank lines between top-level definitions, be they function or class definitions. One blank line between method definitions and between the docstring of a
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
249 and the first method. No blank line following a def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
250 line. Use single blank lines as you judge appropriate within functions or methodsBlank lines need not be anchored to the definition. For example, related comments immediately preceding function, class, and method definitions can make sense. Consider if your comment might be more useful as part of the docstring
3. 6 Whitespace
Follow standard typographic rules for the use of spaces around punctuation
No whitespace inside parentheses, brackets or braces
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
36def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
37No whitespace before a comma, semicolon, or colon. Do use whitespace after a comma, semicolon, or colon, except at the end of the line
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
38def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
39No whitespace before the open paren/bracket that starts an argument list, indexing or slicing
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
40def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
41No trailing whitespace
Surround binary operators with a single space on either side for assignment [
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
251], comparisons [def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
252], and Booleans [def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
253]. Use your better judgment for the insertion of spaces around arithmetic operators [def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
254, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
255, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
256, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
257, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
258, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
259, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
260, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
222]Never use spaces around
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
251 when passing keyword arguments or defining a default parameter value, with one exception. when a type annotation is present, do use spaces around the def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
251 for the default parameter valuedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
42def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
43Don’t use spaces to vertically align tokens on consecutive lines, since it becomes a maintenance burden [applies to
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
264, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
265, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
251, etc. ]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
44def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
453. 7 Shebang Line
Most
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
267 files do not need to start with a def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
268 line. Start the main file of a program with def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
269 [to support virtualenvs] or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
270 per PEP-394This line is used by the kernel to find the Python interpreter, but is ignored by Python when importing modules. It is only necessary on a file intended to be executed directly
Be sure to use the right style for module, function, method docstrings and inline comments
3. 8. 1 Docstrings
Python uses docstrings to document code. A docstring is a string that is the first statement in a package, module, class or function. These strings can be extracted automatically through the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
271 member of the object and are used by def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
225. [Try running def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
225 on your module to see how it looks. ] Always use the three double-quote def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
274 format for docstrings [per PEP 257]. A docstring should be organized as a summary line [one physical line not exceeding 80 characters] terminated by a period, question mark, or exclamation point. When writing more [encouraged], this must be followed by a blank line, followed by the rest of the docstring starting at the same cursor position as the first quote of the first line. There are more formatting guidelines for docstrings below3. 8. 2 Modules
Every file should contain license boilerplate. Choose the appropriate boilerplate for the license used by the project [for example, Apache 2. 0, BSD, LGPL, GPL]
Files should start with a docstring describing the contents and usage of the module
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
463. 8. 2. 1 Test modulesModule-level docstrings for test files are not required. They should be included only when there is additional information that can be provided
Examples include some specifics on how the test should be run, an explanation of an unusual setup pattern, dependency on the external environment, and so on
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
47Docstrings that do not provide any new information should not be used
3. 8. 3 Functions and Methods
In this section, “function” means a method, function, generator, or property
A docstring is mandatory for every function that has one or more of the following properties
- being part of the public API
- nontrivial size
- non-obvious logic
A docstring should give enough information to write a call to the function without reading the function’s code. The docstring should describe the function’s calling syntax and its semantics, but generally not its implementation details, unless those details are relevant to how the function is to be used. For example, a function that mutates one of its arguments as a side effect should note that in its docstring. Otherwise, subtle but important details of a function’s implementation that are not relevant to the caller are better expressed as comments alongside the code than within the function’s docstring
The docstring may be descriptive-style [
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
275] or imperative-style [def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
276], but the style should be consistent within a file. The docstring for a def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
91 data descriptor should use the same style as the docstring for an attribute or a function argument [def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
278, rather than def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
279]A method that overrides a method from a base class may have a simple docstring sending the reader to its overridden method’s docstring, such as
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
280. The rationale is that there is no need to repeat in many places documentation that is already present in the base method’s docstring. However, if the overriding method’s behavior is substantially different from the overridden method, or details need to be provided [e. g. , documenting additional side effects], a docstring with at least those differences is required on the overriding methodCertain aspects of a function should be documented in special sections, listed below. Each section begins with a heading line, which ends with a colon. All sections other than the heading should maintain a hanging indent of two or four spaces [be consistent within a file]. These sections can be omitted in cases where the function’s name and signature are informative enough that it can be aptly described using a one-line docstring
Args. List each parameter by name. A description should follow the name, and be separated by a colon followed by either a space or newline. If the description is too long to fit on a single 80-character line, use a hanging indent of 2 or 4 spaces more than the parameter name [be consistent with the rest of the docstrings in the file]. The description should include required type[s] if the code does not contain a corresponding type annotation. If a function acceptsdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
281 [variable length argument lists] and/or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
282 [arbitrary keyword arguments], they should be listed as def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
281 and def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
282. Returns. [or Yields. for generators]Describe the type and semantics of the return value. If the function only returns None, this section is not required. It may also be omitted if the docstring starts with Returns or Yields [e. g. def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
285] and the opening sentence is sufficient to describe the return value. Do not imitate ‘NumPy style’ [example], which frequently documents a tuple return value as if it were multiple return values with individual names [never mentioning the tuple]. Instead, describe such a return value as. “Returns. A tuple [mat_a, mat_b], where mat_a is …, and …”. The auxiliary names in the docstring need not necessarily correspond to any internal names used in the function body [as those are not part of the API]. Raises. List all exceptions that are relevant to the interface followed by a description. Use a similar exception name + colon + space or newline and hanging indent style as described in Args. You should not document exceptions that get raised if the API specified in the docstring is violated [because this would paradoxically make behavior under violation of the API part of the API]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
48Similarly, this variation on
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
286 with a line break is also alloweddef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
493. 8. 4 Classes
Classes should have a docstring below the class definition describing the class. If your class has public attributes, they should be documented here in an
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
287 section and follow the same formatting as a function’s def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
288 sectiondef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
70All class docstrings should start with a one-line summary that describes what the class instance represents. This implies that subclasses of
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
60 should also describe what the exception represents, and not the context in which it might occur. The class docstring should not repeat unnecessary information, such as that the class is a classdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
71def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
723. 8. 5 Block and Inline Comments
The final place to have comments is in tricky parts of the code. If you’re going to have to explain it at the next code review, you should comment it now. Complicated operations get a few lines of comments before the operations commence. Non-obvious ones get comments at the end of the line
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
73To improve legibility, these comments should start at least 2 spaces away from the code with the comment character
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
265, followed by at least one space before the text of the comment itselfOn the other hand, never describe the code. Assume the person reading the code knows Python [though not what you’re trying to do] better than you do
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
743. 8. 6 Punctuation, Spelling, and Grammar
Pay attention to punctuation, spelling, and grammar; it is easier to read well-written comments than badly written ones
Comments should be as readable as narrative text, with proper capitalization and punctuation. In many cases, complete sentences are more readable than sentence fragments. Shorter comments, such as comments at the end of a line of code, can sometimes be less formal, but you should be consistent with your style
Although it can be frustrating to have a code reviewer point out that you are using a comma when you should be using a semicolon, it is very important that source code maintain a high level of clarity and readability. Proper punctuation, spelling, and grammar help with that goal
3. 10 Strings
Use an f-string, the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
259 operator, or the def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
292 method for formatting strings, even when the parameters are all strings. Use your best judgment to decide between string formatting options. A single join with def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
254 is okay but do not format with def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
254def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
75def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
76Avoid using the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
254 and def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
296 operators to accumulate a string within a loop. In some conditions, accumulating a string with addition can lead to quadratic rather than linear running time. Although common accumulations of this sort may be optimized on CPython, that is an implementation detail. The conditions under which an optimization applies are not easy to predict and may change. Instead, add each substring to a list and def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
297 the list after the loop terminates, or write each substring to an def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
298 buffer. These techniques consistently have amortized-linear run time complexitydef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
77def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
78Be consistent with your choice of string quote character within a file. Pick
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
299 or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
300 and stick with it. It is okay to use the other quote character on a string to avoid the need to backslash-escape quote characters within the stringdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
79dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
50Prefer
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
274 for multi-line strings rather than def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
302. Projects may choose to use def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
302 for all non-docstring multi-line strings if and only if they also use def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
299 for regular strings. Docstrings must use def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
274 regardlessMulti-line strings do not flow with the indentation of the rest of the program. If you need to avoid embedding extra space in the string, use either concatenated single-line strings or a multi-line string with
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
306 to remove the initial space on each linedict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
51dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
52dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
53dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
54dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
553. 10. 1 Logging
For logging functions that expect a pattern-string [with %-placeholders] as their first argument. Always call them with a string literal [not an f-string. ] as their first argument with pattern-parameters as subsequent arguments. Some logging implementations collect the unexpanded pattern-string as a queryable field. It also prevents spending time rendering a message that no logger is configured to output
dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
56dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
57dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
583. 10. 2 Error Messages
Error messages [such as. message strings on exceptions like
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
54, or messages shown to the user] should follow three guidelinesThe message needs to precisely match the actual error condition
Interpolated pieces need to always be clearly identifiable as such
They should allow simple automated processing [e. g. grepping]
dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
59dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
603. 11 Files, Sockets, and similar Stateful Resources
Explicitly close files and sockets when done with them. This rule naturally extends to closeable resources that internally use sockets, such as database connections, and also other resources that need to be closed down in a similar fashion. To name only a few examples, this also includes mmap mappings, h5py File objects, and matplotlib. pyplot figure windows
Leaving files, sockets or other such stateful objects open unnecessarily has many downsides
- They may consume limited system resources, such as file descriptors. Code that deals with many such objects may exhaust those resources unnecessarily if they’re not returned to the system promptly after use
- Holding files open may prevent other actions such as moving or deleting them, or unmounting a filesystem
- Files and sockets that are shared throughout a program may inadvertently be read from or written to after logically being closed. If they are actually closed, attempts to read or write from them will raise exceptions, making the problem known sooner
Furthermore, while files and sockets [and some similarly behaving resources] are automatically closed when the object is destructed, coupling the lifetime of the object to the state of the resource is poor practice
- There are no guarantees as to when the runtime will actually invoke the
233 method. Different Python implementations use different memory management techniques, such as delayed garbage collection, which may increase the object’s lifetime arbitrarily and indefinitelydef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
- Unexpected references to the file, e. g. in globals or exception tracebacks, may keep it around longer than intended
Relying on finalizers to do automatic cleanup that has observable side effects has been rediscovered over and over again to lead to major problems, across many decades and multiple languages [see e. g. this article for Java]
The preferred way to manage files and similar resources is using the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
242 statementdict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
61For file-like objects that do not support the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
242 statement, use def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
311dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
62In rare cases where context-based resource management is infeasible, code documentation must explain clearly how resource lifetime is managed
Use
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
312 comments for code that is temporary, a short-term solution, or good-enough but not perfectA
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
312 comment begins with the word def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
312 in all caps, and a parenthesized context identifier. Ideally a bug reference, sometimes a username. A bug reference like def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
315 is preferable, because bugs are tracked and have follow-up comments, whereas individuals move around and may lose context over time. The def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
312 is followed by an explanation of what there is to doThe purpose is to have a consistent
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
312 format that can be searched to find out how to get more details. A def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
312 is not a commitment that the person referenced will fix the problem. Thus when you create a def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
312 with a username, it is almost always your own username that is givendict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
63If your
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
312 is of the form “At a future date do something” make sure that you either include a very specific date [“Fix by November 2009”] or a very specific event [“Remove this code when all clients can handle XML responses. ”] that future code maintainers will comprehend3. 13 Imports formatting
Imports should be on separate lines; there are exceptions for
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
321 and def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
322 importsE. g
dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
64Imports are always put at the top of the file, just after any module comments and docstrings and before module globals and constants. Imports should be grouped from most generic to least generic
Python future import statements. For example
65dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
See above for more information about those
Python standard library imports. For example
third-party module or package imports. For example
Code repository sub-package imports. For example
66dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
Deprecated. application-specific imports that are part of the same top level sub-package as this file. For example
67dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
You may find older Google Python Style code doing this, but it is no longer required. New code is encouraged not to bother with this. Simply treat application-specific sub-package imports the same as other sub-package imports
Within each grouping, imports should be sorted lexicographically, ignoring case, according to each module’s full package path [the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
323 in def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
324]. Code may optionally place a blank line between import sectionsdict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
683. 14 Statements
Generally only one statement per line
However, you may put the result of a test on the same line as the test only if the entire statement fits on one line. In particular, you can never do so with
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
63/def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
64 since the def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
63 and def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
64 can’t both fit on the same line, and you can only do so with an def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
329 if there is no def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
330dict = 'something awful' # Bad Idea.. pylint: disable=redefined-builtin
693. 15 Getters and Setters
Getter and setter functions [also called accessors and mutators] should be used when they provide a meaningful role or behavior for getting or setting a variable’s value
In particular, they should be used when getting or setting the variable is complex or the cost is significant, either currently or in a reasonable future
If, for example, a pair of getters/setters simply read and write an internal attribute, the internal attribute should be made public instead. By comparison, if setting a variable means some state is invalidated or rebuilt, it should be a setter function. The function invocation hints that a potentially non-trivial operation is occurring. Alternatively, properties may be an option when simple logic is needed, or refactoring to no longer need getters and setters
Getters and setters should follow the Naming guidelines, such as
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
331 and def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
332If the past behavior allowed access through a property, do not bind the new getter/setter functions to the property. Any code still attempting to access the variable by the old method should break visibly so they are made aware of the change in complexity
3. 16 Naming
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
333, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
334, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
335, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
336, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
337, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
338, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
339, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
340, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
341, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
342, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
343, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
344, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
345Function names, variable names, and filenames should be descriptive; avoid abbreviation. In particular, do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word
Always use a
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
267 filename extension. Never use dashes3. 16. 1 Names to Avoid
single character names, except for specifically allowed cases
- counters or iterators [e. g.
347,def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
348,def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
349,def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
350, et al. ]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
351 as an exception identifier indef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
352 statementsdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
353 as a file handle indef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
242 statementsdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
- private
355s with no constraints [e. g.def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
356,def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
357,def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
358]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Please be mindful not to abuse single-character naming. Generally speaking, descriptiveness should be proportional to the name’s scope of visibility. For example,
347 might be a fine name for 5-line code block but within multiple nested scopes, it is likely too vaguedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
- counters or iterators [e. g.
dashes [
255] in any package/module namedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
361 names [reserved by Python]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
offensive terms
names that needlessly include the type of the variable [for example.
362]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
3. 16. 2 Naming Conventions
“Internal” means internal to a module, or protected or private within a class
Prepending a single underscore [
28] has some support for protecting module variables and functions [linters will flag protected member access]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Prepending a double underscore [
364 aka “dunder”] to an instance variable or method effectively makes the variable or method private to its class [using name mangling]; we discourage its use as it impacts readability and testability, and isn’t really private. Prefer a single underscoredef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module
Use CapWords for class names, but lower_with_under. py for module names. Although there are some old modules named CapWords. py, this is now discouraged because it’s confusing when the module happens to be named after a class. [“wait – did I write
365 ordef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
366?”]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Underscores may appear in unittest method names starting with
367 to separate logical components of the name, even if those components use CapWords. One possible pattern isdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
368; for exampledef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
369 is okay. There is no One Correct Way to name test methodsdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
3. 16. 3 File Naming
Python filenames must have a
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
267 extension and must not contain dashes [def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
255]. This allows them to be imported and unittested. If you want an executable to be accessible without the extension, use a symbolic link or a simple bash wrapper containing def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
3723. 16. 4 Guidelines derived from Guido’s Recommendations
TypePublicInternalPackagesdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
373Modulesdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
373def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
375Classesdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
376def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
377Exceptionsdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
376Functionsdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
379def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
380Global/Class Constantsdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
381def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
382Global/Class Variablesdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
373def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
375Instance Variablesdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
373def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
375 [protected]Method Namesdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
379def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
380 [protected]Function/Method Parametersdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
373Local Variablesdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
3733. 16. 5 Mathematical Notation
For mathematically heavy code, short variable names that would otherwise violate the style guide are preferred when they match established notation in a reference paper or algorithm. When doing so, reference the source of all naming conventions in a comment or docstring or, if the source is not accessible, clearly document the naming conventions. Prefer PEP8-compliant
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
391 for public APIs, which are much more likely to be encountered out of context3. 17 Main
In Python,
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
225 as well as unit tests require modules to be importable. If a file is meant to be used as an executable, its main functionality should be in a def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
393 function, and your code should always check def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
394 before executing your main program, so that it is not executed when the module is importedWhen using absl, use
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
395def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
00Otherwise, use
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
01All code at the top level will be executed when the module is imported. Be careful not to call functions, create objects, or perform other operations that should not be executed when the file is being
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
225ed3. 18 Function length
Prefer small and focused functions
We recognize that long functions are sometimes appropriate, so no hard limit is placed on function length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program
Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code
You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code. if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces
3. 19 Type Annotations
3. 19. 1 General Rules
Familiarize yourself with PEP-484
In methods, only annotate
73, ordef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
74 if it is necessary for proper type information. e. g. ,def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
02def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Similarly, don’t feel compelled to annotate the return value of
399 [wheredef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
98 is the only valid option]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
If any other variable or a returned type should not be expressed, use
401def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
You are not required to annotate all the functions in a module
- At least annotate your public APIs
- Use judgment to get to a good balance between safety and clarity on the one hand, and flexibility on the other
- Annotate code that is prone to type-related errors [previous bugs or complexity]
- Annotate code that is hard to understand
- Annotate code as it becomes stable from a types perspective. In many cases, you can annotate all the functions in mature code without losing too much flexibility
3. 19. 2 Line Breaking
Try to follow the existing indentation rules
After annotating, many function signatures will become “one parameter per line”. To ensure the return type is also given its own line, a comma can be placed after the last parameter
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
03Always prefer breaking between variables, and not, for example, between variable names and type annotations. However, if everything fits on the same line, go for it
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
04If the combination of the function name, the last parameter, and the return type is too long, indent by 4 in a new line. When using line breaks, prefer putting each parameter and the return type on their own lines and aligning the closing parenthesis with the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
250def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
05Optionally, the return type may be put on the same line as the last parameter
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
06def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
18 allows you to move the closing parenthesis to a new line and align with the opening one, but this is less readabledef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
07As in the examples above, prefer not to break types. However, sometimes they are too long to be on a single line [try to keep sub-types unbroken]
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
08If a single name and type is too long, consider using an alias for the type. The last resort is to break after the colon and indent by 4
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
09def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
103. 19. 3 Forward Declarations
If you need to use a class name [from the same module] that is not yet defined – for example, if you need the class name inside the declaration of that class, or if you use a class that is defined later in the code – either use
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
404 or use a string for the class namedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
11def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
123. 19. 4 Default Values
As per PEP-008, use spaces around the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
251 only for arguments that have both a type annotation and a default valuedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
13def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
143. 19. 5 NoneType
In the Python type system,
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
406 is a “first class” type, and for typing purposes, def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
98 is an alias for def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
406. If an argument can be def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
98, it has to be declared. You can use def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
410, but if there is only one other type, use def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
411Use explicit
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
411 instead of implicit def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
411. Earlier versions of PEP 484 allowed def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
414 to be interpreted as def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
415, but that is no longer the preferred behaviordef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
15def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
163. 19. 6 Type Aliases
You can declare aliases of complex types. The name of an alias should be CapWorded. If the alias is used only in this module, it should be _Private
For example, if the name of the module together with the name of the type is too long
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
17Other examples are complex nested types and multiple return variables from a function [as a tuple]
3. 19. 7 Ignoring Types
You can disable type checking on a line with the special comment
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
416def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
417 has a disable option for specific errors [similar to lint]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
183. 19. 8 Typing Variables
Annotated AssignmentsIf an internal variable has a type that is hard or impossible to infer, specify its type with an annotated assignment - use a colon and type between the variable name and value [the same as is done with function arguments that have a default value]def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
19Type CommentsThough you may see them remaining in the codebase [they were necessary before Python 3. 6], do not add any more uses of a def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
418 comment on the end of the linedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
003. 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
013. 19. 10 TypeVars
The Python type system has generics. The factory function
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
355 is a common way to use themExample
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
02A 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
03A common predefined type variable in the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
321 module is def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
421. Use it for multiple annotations that can be def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
422 or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
423 and must all be the same typedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
04A 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
05def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
063. 19. 11 String types
Do not use
424 in new code. It’s only for Python 2/3 compatibilitydef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
Use
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
423 for string/text data. For code that deals with binary data, use def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
422def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
07If all the string types of a function are always the same, for example if the return type is the same as the argument type in the code above, use AnyStr
3. 19. 12 Imports For Typing
For symbols from the
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
321 and def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
322 modules used to support static analysis and type checking, always import the symbol itself. This keeps common annotations more concise and matches typing practices used around the world. You are explicitly allowed to import multiple specific classes on one line from the def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
321 and def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
322 modules. Exdef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
08Given that this way of importing adds items to the local namespace, names in
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
321 or def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
322 should be treated similarly to keywords, and not be defined in your Python code, typed or not. If there is a collision between a type and an existing name in a module, import it using def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
433def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
09Prefer 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
10NOTE. Users of Apache Beam should continue to import parametric containers from
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
321def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
113. 19. 13 Conditional Imports
Use conditional imports only in exceptional cases where the additional imports needed for type checking must be avoided at runtime. This pattern is discouraged; alternatives such as refactoring the code to allow top level imports should be preferred
Imports that are needed only for type annotations can be placed within an
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
435 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
12def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str: del beans, eggs # Unused by vikings. return spam + spam + spam
3. 19. 14 Circular Dependencies
Circular dependencies that are caused by typing are code smells. Such code is a good candidate for refactoring. Although technically it is possible to keep circular dependencies, various build systems will not let you do so because each module has to depend on the other
Replace modules that create circular dependency imports with
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
401. Set an alias with a meaningful name, and use the real type name from this module [any attribute of Any is Any]. Alias definitions should be separated from the last import by one linedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
133. 19. 15 Generics
When annotating, prefer to specify type parameters for generic types; otherwise, the generics’ parameters will be assumed to be
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
401def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
14def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
15If the best type parameter for a generic is
def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
401, make it explicit, but remember that in many cases def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
355 might be more appropriatedef viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
16def viking_cafe_order[spam: str, beans: str, eggs: Optional[str] = None] -> str:
del beans, eggs # Unused by vikings.
return spam + spam + spam
174 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