xref: /aosp_15_r20/external/google-styleguide/pyguide.md (revision 8c35d5ee8e2913d4bd6623e2b93232b1da0ab719)
1*8c35d5eeSXin Li<!--
2*8c35d5eeSXin LiAUTHORS:
3*8c35d5eeSXin LiPrefer only GitHub-flavored Markdown in external text.
4*8c35d5eeSXin LiSee README.md for details.
5*8c35d5eeSXin Li-->
6*8c35d5eeSXin Li
7*8c35d5eeSXin Li# Google Python Style Guide
8*8c35d5eeSXin Li
9*8c35d5eeSXin Li
10*8c35d5eeSXin Li<a id="1-background"></a>
11*8c35d5eeSXin Li
12*8c35d5eeSXin Li<a id="background"></a>
13*8c35d5eeSXin Li## 1 Background
14*8c35d5eeSXin Li
15*8c35d5eeSXin LiPython is the main dynamic language used at Google. This style guide is a list
16*8c35d5eeSXin Liof *dos and don'ts* for Python programs.
17*8c35d5eeSXin Li
18*8c35d5eeSXin LiTo help you format code correctly, we've created a [settings file for
19*8c35d5eeSXin LiVim](google_python_style.vim). For Emacs, the default settings should be fine.
20*8c35d5eeSXin Li
21*8c35d5eeSXin LiMany teams use the [yapf](https://github.com/google/yapf/)
22*8c35d5eeSXin Liauto-formatter to avoid arguing over formatting.
23*8c35d5eeSXin Li
24*8c35d5eeSXin Li
25*8c35d5eeSXin Li<a id="s2-python-language-rules"></a>
26*8c35d5eeSXin Li<a id="2-python-language-rules"></a>
27*8c35d5eeSXin Li
28*8c35d5eeSXin Li<a id="python-language-rules"></a>
29*8c35d5eeSXin Li## 2 Python Language Rules
30*8c35d5eeSXin Li
31*8c35d5eeSXin Li<a id="s2.1-lint"></a>
32*8c35d5eeSXin Li<a id="21-lint"></a>
33*8c35d5eeSXin Li
34*8c35d5eeSXin Li<a id="lint"></a>
35*8c35d5eeSXin Li### 2.1 Lint
36*8c35d5eeSXin Li
37*8c35d5eeSXin LiRun `pylint` over your code.
38*8c35d5eeSXin Li
39*8c35d5eeSXin Li<a id="s2.1.1-definition"></a>
40*8c35d5eeSXin Li<a id="211-definition"></a>
41*8c35d5eeSXin Li
42*8c35d5eeSXin Li<a id="lint-definition"></a>
43*8c35d5eeSXin Li#### 2.1.1 Definition
44*8c35d5eeSXin Li
45*8c35d5eeSXin Li`pylint` is a tool for finding bugs and style problems in Python source
46*8c35d5eeSXin Licode. It finds problems that are typically caught by a compiler for less dynamic
47*8c35d5eeSXin Lilanguages like C and C++. Because of the dynamic nature of Python, some
48*8c35d5eeSXin Liwarnings may be incorrect; however, spurious warnings should be fairly
49*8c35d5eeSXin Liinfrequent.
50*8c35d5eeSXin Li
51*8c35d5eeSXin Li<a id="s2.1.2-pros"></a>
52*8c35d5eeSXin Li<a id="212-pros"></a>
53*8c35d5eeSXin Li
54*8c35d5eeSXin Li<a id="lint-pros"></a>
55*8c35d5eeSXin Li#### 2.1.2 Pros
56*8c35d5eeSXin Li
57*8c35d5eeSXin LiCatches easy-to-miss errors like typos, using-vars-before-assignment, etc.
58*8c35d5eeSXin Li
59*8c35d5eeSXin Li<a id="s2.1.3-cons"></a>
60*8c35d5eeSXin Li<a id="213-cons"></a>
61*8c35d5eeSXin Li
62*8c35d5eeSXin Li<a id="lint-cons"></a>
63*8c35d5eeSXin Li#### 2.1.3 Cons
64*8c35d5eeSXin Li
65*8c35d5eeSXin Li`pylint` isn't perfect. To take advantage of it, we'll need to sometimes: a)
66*8c35d5eeSXin LiWrite around it b) Suppress its warnings or c) Improve it.
67*8c35d5eeSXin Li
68*8c35d5eeSXin Li<a id="s2.1.4-decision"></a>
69*8c35d5eeSXin Li<a id="214-decision"></a>
70*8c35d5eeSXin Li
71*8c35d5eeSXin Li<a id="lint-decision"></a>
72*8c35d5eeSXin Li#### 2.1.4 Decision
73*8c35d5eeSXin Li
74*8c35d5eeSXin LiMake sure you run `pylint` on your code.
75*8c35d5eeSXin Li
76*8c35d5eeSXin Li
77*8c35d5eeSXin LiSuppress warnings if they are inappropriate so that other issues are not hidden.
78*8c35d5eeSXin LiTo suppress warnings, you can set a line-level comment:
79*8c35d5eeSXin Li
80*8c35d5eeSXin Li```python
81*8c35d5eeSXin Lidict = 'something awful'  # Bad Idea... pylint: disable=redefined-builtin
82*8c35d5eeSXin Li```
83*8c35d5eeSXin Li
84*8c35d5eeSXin Li`pylint` warnings are each identified by symbolic name (`empty-docstring`)
85*8c35d5eeSXin LiGoogle-specific warnings start with `g-`.
86*8c35d5eeSXin Li
87*8c35d5eeSXin LiIf the reason for the suppression is not clear from the symbolic name, add an
88*8c35d5eeSXin Liexplanation.
89*8c35d5eeSXin Li
90*8c35d5eeSXin LiSuppressing in this way has the advantage that we can easily search for
91*8c35d5eeSXin Lisuppressions and revisit them.
92*8c35d5eeSXin Li
93*8c35d5eeSXin LiYou can get a list of `pylint` warnings by doing:
94*8c35d5eeSXin Li
95*8c35d5eeSXin Li```shell
96*8c35d5eeSXin Lipylint --list-msgs
97*8c35d5eeSXin Li```
98*8c35d5eeSXin Li
99*8c35d5eeSXin LiTo get more information on a particular message, use:
100*8c35d5eeSXin Li
101*8c35d5eeSXin Li```shell
102*8c35d5eeSXin Lipylint --help-msg=C6409
103*8c35d5eeSXin Li```
104*8c35d5eeSXin Li
105*8c35d5eeSXin LiPrefer `pylint: disable` to the deprecated older form `pylint: disable-msg`.
106*8c35d5eeSXin Li
107*8c35d5eeSXin LiUnused argument warnings can be suppressed by deleting the variables at the
108*8c35d5eeSXin Libeginning of the function. Always include a comment explaining why you are
109*8c35d5eeSXin Lideleting it. "Unused." is sufficient. For example:
110*8c35d5eeSXin Li
111*8c35d5eeSXin Li```python
112*8c35d5eeSXin Lidef viking_cafe_order(spam, beans, eggs=None):
113*8c35d5eeSXin Li    del beans, eggs  # Unused by vikings.
114*8c35d5eeSXin Li    return spam + spam + spam
115*8c35d5eeSXin Li```
116*8c35d5eeSXin Li
117*8c35d5eeSXin LiOther common forms of suppressing this warning include using '`_`' as the
118*8c35d5eeSXin Liidentifier for the unused argument, prefixing the argument name with
119*8c35d5eeSXin Li'`unused_`', or assigning them to '`_`'. These forms are allowed but no longer
120*8c35d5eeSXin Liencouraged. The first two break callers that pass arguments by name, while the
121*8c35d5eeSXin Lilast does not enforce that the arguments are actually unused.
122*8c35d5eeSXin Li
123*8c35d5eeSXin Li<a id="s2.2-imports"></a>
124*8c35d5eeSXin Li<a id="22-imports"></a>
125*8c35d5eeSXin Li
126*8c35d5eeSXin Li<a id="imports"></a>
127*8c35d5eeSXin Li### 2.2 Imports
128*8c35d5eeSXin Li
129*8c35d5eeSXin LiUse `import` statements for packages and modules only, not for individual
130*8c35d5eeSXin Liclasses or functions. Note that there is an explicit exemption for imports from
131*8c35d5eeSXin Lithe [typing module](#typing-imports).
132*8c35d5eeSXin Li
133*8c35d5eeSXin Li<a id="s2.2.1-definition"></a>
134*8c35d5eeSXin Li<a id="221-definition"></a>
135*8c35d5eeSXin Li
136*8c35d5eeSXin Li<a id="imports-definition"></a>
137*8c35d5eeSXin Li#### 2.2.1 Definition
138*8c35d5eeSXin Li
139*8c35d5eeSXin LiReusability mechanism for sharing code from one module to another.
140*8c35d5eeSXin Li
141*8c35d5eeSXin Li<a id="s2.2.2-pros"></a>
142*8c35d5eeSXin Li<a id="222-pros"></a>
143*8c35d5eeSXin Li
144*8c35d5eeSXin Li<a id="imports-pros"></a>
145*8c35d5eeSXin Li#### 2.2.2 Pros
146*8c35d5eeSXin Li
147*8c35d5eeSXin LiThe namespace management convention is simple. The source of each identifier is
148*8c35d5eeSXin Liindicated in a consistent way; `x.Obj` says that object `Obj` is defined in
149*8c35d5eeSXin Limodule `x`.
150*8c35d5eeSXin Li
151*8c35d5eeSXin Li<a id="s2.2.3-cons"></a>
152*8c35d5eeSXin Li<a id="223-cons"></a>
153*8c35d5eeSXin Li
154*8c35d5eeSXin Li<a id="imports-cons"></a>
155*8c35d5eeSXin Li#### 2.2.3 Cons
156*8c35d5eeSXin Li
157*8c35d5eeSXin LiModule names can still collide. Some module names are inconveniently long.
158*8c35d5eeSXin Li
159*8c35d5eeSXin Li<a id="s2.2.4-decision"></a>
160*8c35d5eeSXin Li<a id="224-decision"></a>
161*8c35d5eeSXin Li
162*8c35d5eeSXin Li<a id="imports-decision"></a>
163*8c35d5eeSXin Li#### 2.2.4 Decision
164*8c35d5eeSXin Li
165*8c35d5eeSXin Li* Use `import x` for importing packages and modules.
166*8c35d5eeSXin Li* Use `from x import y` where `x` is the package prefix and `y` is the module
167*8c35d5eeSXin Liname with no prefix.
168*8c35d5eeSXin Li* Use `from x import y as z` if two modules named `y` are to be imported or if
169*8c35d5eeSXin Li`y` is an inconveniently long name.
170*8c35d5eeSXin Li* Use `import y as z` only when `z` is a standard abbreviation (e.g., `np` for
171*8c35d5eeSXin Li`numpy`).
172*8c35d5eeSXin Li
173*8c35d5eeSXin LiFor example the module `sound.effects.echo` may be imported as follows:
174*8c35d5eeSXin Li
175*8c35d5eeSXin Li```python
176*8c35d5eeSXin Lifrom sound.effects import echo
177*8c35d5eeSXin Li...
178*8c35d5eeSXin Liecho.EchoFilter(input, output, delay=0.7, atten=4)
179*8c35d5eeSXin Li```
180*8c35d5eeSXin Li
181*8c35d5eeSXin LiDo not use relative names in imports. Even if the module is in the same package,
182*8c35d5eeSXin Liuse the full package name. This helps prevent unintentionally importing a
183*8c35d5eeSXin Lipackage twice.
184*8c35d5eeSXin Li
185*8c35d5eeSXin LiImports from the [typing module](#typing-imports) and the
186*8c35d5eeSXin Li[six.moves module](https://six.readthedocs.io/#module-six.moves)
187*8c35d5eeSXin Liare exempt from this rule.
188*8c35d5eeSXin Li
189*8c35d5eeSXin Li<a id="s2.3-packages"></a>
190*8c35d5eeSXin Li<a id="23-packages"></a>
191*8c35d5eeSXin Li
192*8c35d5eeSXin Li<a id="packages"></a>
193*8c35d5eeSXin Li### 2.3 Packages
194*8c35d5eeSXin Li
195*8c35d5eeSXin LiImport each module using the full pathname location of the module.
196*8c35d5eeSXin Li
197*8c35d5eeSXin Li<a id="s2.3.1-pros"></a>
198*8c35d5eeSXin Li<a id="231-pros"></a>
199*8c35d5eeSXin Li
200*8c35d5eeSXin Li<a id="packages-pros"></a>
201*8c35d5eeSXin Li#### 2.3.1 Pros
202*8c35d5eeSXin Li
203*8c35d5eeSXin LiAvoids conflicts in module names or incorrect imports due to the module search
204*8c35d5eeSXin Lipath not being what the author expected.  Makes it easier to find modules.
205*8c35d5eeSXin Li
206*8c35d5eeSXin Li<a id="s2.3.2-cons"></a>
207*8c35d5eeSXin Li<a id="232-cons"></a>
208*8c35d5eeSXin Li
209*8c35d5eeSXin Li<a id="packages-cons"></a>
210*8c35d5eeSXin Li#### 2.3.2 Cons
211*8c35d5eeSXin Li
212*8c35d5eeSXin LiMakes it harder to deploy code because you have to replicate the package
213*8c35d5eeSXin Lihierarchy.  Not really a problem with modern deployment mechanisms.
214*8c35d5eeSXin Li
215*8c35d5eeSXin Li<a id="s2.3.3-decision"></a>
216*8c35d5eeSXin Li<a id="233-decision"></a>
217*8c35d5eeSXin Li
218*8c35d5eeSXin Li<a id="packages-decision"></a>
219*8c35d5eeSXin Li#### 2.3.3 Decision
220*8c35d5eeSXin Li
221*8c35d5eeSXin LiAll new code should import each module by its full package name.
222*8c35d5eeSXin Li
223*8c35d5eeSXin LiImports should be as follows:
224*8c35d5eeSXin Li
225*8c35d5eeSXin LiYes:
226*8c35d5eeSXin Li
227*8c35d5eeSXin Li```python
228*8c35d5eeSXin Li# Reference absl.flags in code with the complete name (verbose).
229*8c35d5eeSXin Liimport absl.flags
230*8c35d5eeSXin Lifrom doctor.who import jodie
231*8c35d5eeSXin Li
232*8c35d5eeSXin LiFLAGS = absl.flags.FLAGS
233*8c35d5eeSXin Li```
234*8c35d5eeSXin Li
235*8c35d5eeSXin Li```python
236*8c35d5eeSXin Li# Reference flags in code with just the module name (common).
237*8c35d5eeSXin Lifrom absl import flags
238*8c35d5eeSXin Lifrom doctor.who import jodie
239*8c35d5eeSXin Li
240*8c35d5eeSXin LiFLAGS = flags.FLAGS
241*8c35d5eeSXin Li```
242*8c35d5eeSXin Li
243*8c35d5eeSXin LiNo: _(assume this file lives in `doctor/who/` where `jodie.py` also exists)_
244*8c35d5eeSXin Li
245*8c35d5eeSXin Li```python
246*8c35d5eeSXin Li# Unclear what module the author wanted and what will be imported.  The actual
247*8c35d5eeSXin Li# import behavior depends on external factors controlling sys.path.
248*8c35d5eeSXin Li# Which possible jodie module did the author intend to import?
249*8c35d5eeSXin Liimport jodie
250*8c35d5eeSXin Li```
251*8c35d5eeSXin Li
252*8c35d5eeSXin LiThe directory the main binary is located in should not be assumed to be in
253*8c35d5eeSXin Li`sys.path` despite that happening in some environments.  This being the case,
254*8c35d5eeSXin Licode should assume that `import jodie` refers to a third party or top level
255*8c35d5eeSXin Lipackage named `jodie`, not a local `jodie.py`.
256*8c35d5eeSXin Li
257*8c35d5eeSXin Li
258*8c35d5eeSXin Li<a id="s2.4-exceptions"></a>
259*8c35d5eeSXin Li<a id="24-exceptions"></a>
260*8c35d5eeSXin Li
261*8c35d5eeSXin Li<a id="exceptions"></a>
262*8c35d5eeSXin Li### 2.4 Exceptions
263*8c35d5eeSXin Li
264*8c35d5eeSXin LiExceptions are allowed but must be used carefully.
265*8c35d5eeSXin Li
266*8c35d5eeSXin Li<a id="s2.4.1-definition"></a>
267*8c35d5eeSXin Li<a id="241-definition"></a>
268*8c35d5eeSXin Li
269*8c35d5eeSXin Li<a id="exceptions-definition"></a>
270*8c35d5eeSXin Li#### 2.4.1 Definition
271*8c35d5eeSXin Li
272*8c35d5eeSXin LiExceptions are a means of breaking out of the normal flow of control of a code
273*8c35d5eeSXin Liblock to handle errors or other exceptional conditions.
274*8c35d5eeSXin Li
275*8c35d5eeSXin Li<a id="s2.4.2-pros"></a>
276*8c35d5eeSXin Li<a id="242-pros"></a>
277*8c35d5eeSXin Li
278*8c35d5eeSXin Li<a id="exceptions-pros"></a>
279*8c35d5eeSXin Li#### 2.4.2 Pros
280*8c35d5eeSXin Li
281*8c35d5eeSXin LiThe control flow of normal operation code is not cluttered by error-handling
282*8c35d5eeSXin Licode. It also allows the control flow to skip multiple frames when a certain
283*8c35d5eeSXin Licondition occurs, e.g., returning from N nested functions in one step instead of
284*8c35d5eeSXin Lihaving to carry-through error codes.
285*8c35d5eeSXin Li
286*8c35d5eeSXin Li<a id="s2.4.3-cons"></a>
287*8c35d5eeSXin Li<a id="243-cons"></a>
288*8c35d5eeSXin Li
289*8c35d5eeSXin Li<a id="exceptions-cons"></a>
290*8c35d5eeSXin Li#### 2.4.3 Cons
291*8c35d5eeSXin Li
292*8c35d5eeSXin LiMay cause the control flow to be confusing. Easy to miss error cases when making
293*8c35d5eeSXin Lilibrary calls.
294*8c35d5eeSXin Li
295*8c35d5eeSXin Li<a id="s2.4.4-decision"></a>
296*8c35d5eeSXin Li<a id="244-decision"></a>
297*8c35d5eeSXin Li
298*8c35d5eeSXin Li<a id="exceptions-decision"></a>
299*8c35d5eeSXin Li#### 2.4.4 Decision
300*8c35d5eeSXin Li
301*8c35d5eeSXin LiExceptions must follow certain conditions:
302*8c35d5eeSXin Li
303*8c35d5eeSXin Li-   Raise exceptions like this: `raise MyError('Error message')` or `raise
304*8c35d5eeSXin Li    MyError()`. Do not use the two-argument form (`raise MyError, 'Error
305*8c35d5eeSXin Li    message'`).
306*8c35d5eeSXin Li
307*8c35d5eeSXin Li-   Make use of built-in exception classes when it makes sense. For example,
308*8c35d5eeSXin Li    raise a `ValueError` to indicate a programming mistake like a violated
309*8c35d5eeSXin Li    precondition (such as if you were passed a negative number but required a
310*8c35d5eeSXin Li    positive one). Do not use `assert` statements for validating argument values
311*8c35d5eeSXin Li    of a public API. `assert` is used to ensure internal correctness, not to
312*8c35d5eeSXin Li    enforce correct usage nor to indicate that some unexpected event occurred.
313*8c35d5eeSXin Li    If an exception is desired in the latter cases, use a raise statement. For
314*8c35d5eeSXin Li    example:
315*8c35d5eeSXin Li
316*8c35d5eeSXin Li
317*8c35d5eeSXin Li    ```python
318*8c35d5eeSXin Li    Yes:
319*8c35d5eeSXin Li      def connect_to_next_port(self, minimum):
320*8c35d5eeSXin Li        """Connects to the next available port.
321*8c35d5eeSXin Li
322*8c35d5eeSXin Li        Args:
323*8c35d5eeSXin Li          minimum: A port value greater or equal to 1024.
324*8c35d5eeSXin Li
325*8c35d5eeSXin Li        Returns:
326*8c35d5eeSXin Li          The new minimum port.
327*8c35d5eeSXin Li
328*8c35d5eeSXin Li        Raises:
329*8c35d5eeSXin Li          ConnectionError: If no available port is found.
330*8c35d5eeSXin Li        """
331*8c35d5eeSXin Li        if minimum < 1024:
332*8c35d5eeSXin Li          # Note that this raising of ValueError is not mentioned in the doc
333*8c35d5eeSXin Li          # string's "Raises:" section because it is not appropriate to
334*8c35d5eeSXin Li          # guarantee this specific behavioral reaction to API misuse.
335*8c35d5eeSXin Li          raise ValueError('Minimum port must be at least 1024, not %d.' % (minimum,))
336*8c35d5eeSXin Li        port = self._find_next_open_port(minimum)
337*8c35d5eeSXin Li        if not port:
338*8c35d5eeSXin Li          raise ConnectionError('Could not connect to service on %d or higher.' % (minimum,))
339*8c35d5eeSXin Li        assert port >= minimum, 'Unexpected port %d when minimum was %d.' % (port, minimum)
340*8c35d5eeSXin Li        return port
341*8c35d5eeSXin Li    ```
342*8c35d5eeSXin Li
343*8c35d5eeSXin Li    ```python
344*8c35d5eeSXin Li    No:
345*8c35d5eeSXin Li      def connect_to_next_port(self, minimum):
346*8c35d5eeSXin Li        """Connects to the next available port.
347*8c35d5eeSXin Li
348*8c35d5eeSXin Li        Args:
349*8c35d5eeSXin Li          minimum: A port value greater or equal to 1024.
350*8c35d5eeSXin Li
351*8c35d5eeSXin Li        Returns:
352*8c35d5eeSXin Li          The new minimum port.
353*8c35d5eeSXin Li        """
354*8c35d5eeSXin Li        assert minimum >= 1024, 'Minimum port must be at least 1024.'
355*8c35d5eeSXin Li        port = self._find_next_open_port(minimum)
356*8c35d5eeSXin Li        assert port is not None
357*8c35d5eeSXin Li        return port
358*8c35d5eeSXin Li    ```
359*8c35d5eeSXin Li
360*8c35d5eeSXin Li-   Libraries or packages may define their own exceptions. When doing so they
361*8c35d5eeSXin Li    must inherit from an existing exception class. Exception names should end in
362*8c35d5eeSXin Li    `Error` and should not introduce stutter (`foo.FooError`).
363*8c35d5eeSXin Li
364*8c35d5eeSXin Li-   Never use catch-all `except:` statements, or catch `Exception` or
365*8c35d5eeSXin Li    `StandardError`, unless you are
366*8c35d5eeSXin Li
367*8c35d5eeSXin Li    -   re-raising the exception, or
368*8c35d5eeSXin Li    -   creating an isolation point in the program where exceptions are not
369*8c35d5eeSXin Li        propagated but are recorded and suppressed instead, such as protecting a
370*8c35d5eeSXin Li        thread from crashing by guarding its outermost block.
371*8c35d5eeSXin Li
372*8c35d5eeSXin Li    Python is very tolerant in this regard and `except:` will really catch
373*8c35d5eeSXin Li    everything including misspelled names, sys.exit() calls, Ctrl+C interrupts,
374*8c35d5eeSXin Li    unittest failures and all kinds of other exceptions that you simply don't
375*8c35d5eeSXin Li    want to catch.
376*8c35d5eeSXin Li
377*8c35d5eeSXin Li-   Minimize the amount of code in a `try`/`except` block. The larger the body
378*8c35d5eeSXin Li    of the `try`, the more likely that an exception will be raised by a line of
379*8c35d5eeSXin Li    code that you didn't expect to raise an exception. In those cases, the
380*8c35d5eeSXin Li    `try`/`except` block hides a real error.
381*8c35d5eeSXin Li
382*8c35d5eeSXin Li-   Use the `finally` clause to execute code whether or not an exception is
383*8c35d5eeSXin Li    raised in the `try` block. This is often useful for cleanup, i.e., closing a
384*8c35d5eeSXin Li    file.
385*8c35d5eeSXin Li
386*8c35d5eeSXin Li-   When capturing an exception, use `as` rather than a comma. For example:
387*8c35d5eeSXin Li
388*8c35d5eeSXin Li
389*8c35d5eeSXin Li    ```python
390*8c35d5eeSXin Li    try:
391*8c35d5eeSXin Li      raise Error()
392*8c35d5eeSXin Li    except Error as error:
393*8c35d5eeSXin Li      pass
394*8c35d5eeSXin Li    ```
395*8c35d5eeSXin Li
396*8c35d5eeSXin Li<a id="s2.5-global-variables"></a>
397*8c35d5eeSXin Li<a id="25-global-variables"></a>
398*8c35d5eeSXin Li
399*8c35d5eeSXin Li<a id="global-variables"></a>
400*8c35d5eeSXin Li### 2.5 Global variables
401*8c35d5eeSXin Li
402*8c35d5eeSXin LiAvoid global variables.
403*8c35d5eeSXin Li
404*8c35d5eeSXin Li<a id="s2.5.1-definition"></a>
405*8c35d5eeSXin Li<a id="251-definition"></a>
406*8c35d5eeSXin Li
407*8c35d5eeSXin Li<a id="global-variables-definition"></a>
408*8c35d5eeSXin Li#### 2.5.1 Definition
409*8c35d5eeSXin Li
410*8c35d5eeSXin LiVariables that are declared at the module level or as class attributes.
411*8c35d5eeSXin Li
412*8c35d5eeSXin Li<a id="s2.5.2-pros"></a>
413*8c35d5eeSXin Li<a id="252-pros"></a>
414*8c35d5eeSXin Li
415*8c35d5eeSXin Li<a id="global-variables-pros"></a>
416*8c35d5eeSXin Li#### 2.5.2 Pros
417*8c35d5eeSXin Li
418*8c35d5eeSXin LiOccasionally useful.
419*8c35d5eeSXin Li
420*8c35d5eeSXin Li<a id="s2.5.3-cons"></a>
421*8c35d5eeSXin Li<a id="253-cons"></a>
422*8c35d5eeSXin Li
423*8c35d5eeSXin Li<a id="global-variables-cons"></a>
424*8c35d5eeSXin Li#### 2.5.3 Cons
425*8c35d5eeSXin Li
426*8c35d5eeSXin LiHas the potential to change module behavior during the import, because
427*8c35d5eeSXin Liassignments to global variables are done when the module is first imported.
428*8c35d5eeSXin Li
429*8c35d5eeSXin Li<a id="s2.5.4-decision"></a>
430*8c35d5eeSXin Li<a id="254-decision"></a>
431*8c35d5eeSXin Li
432*8c35d5eeSXin Li<a id="global-variables-decision"></a>
433*8c35d5eeSXin Li#### 2.5.4 Decision
434*8c35d5eeSXin Li
435*8c35d5eeSXin LiAvoid global variables.
436*8c35d5eeSXin Li
437*8c35d5eeSXin LiWhile they are technically variables, module-level constants are permitted and
438*8c35d5eeSXin Liencouraged. For example: `MAX_HOLY_HANDGRENADE_COUNT = 3`. Constants must be
439*8c35d5eeSXin Linamed using all caps with underscores. See [Naming](#s3.16-naming) below.
440*8c35d5eeSXin Li
441*8c35d5eeSXin LiIf needed, globals should be declared at the module level and made internal to
442*8c35d5eeSXin Lithe module by prepending an `_` to the name. External access must be done
443*8c35d5eeSXin Lithrough public module-level functions. See [Naming](#s3.16-naming) below.
444*8c35d5eeSXin Li
445*8c35d5eeSXin Li<a id="s2.6-nested"></a>
446*8c35d5eeSXin Li<a id="26-nested"></a>
447*8c35d5eeSXin Li
448*8c35d5eeSXin Li<a id="nested-classes-functions"></a>
449*8c35d5eeSXin Li### 2.6 Nested/Local/Inner Classes and Functions
450*8c35d5eeSXin Li
451*8c35d5eeSXin LiNested local functions or classes are fine when used to close over a local
452*8c35d5eeSXin Livariable. Inner classes are fine.
453*8c35d5eeSXin Li
454*8c35d5eeSXin Li<a id="s2.6.1-definition"></a>
455*8c35d5eeSXin Li<a id="261-definition"></a>
456*8c35d5eeSXin Li
457*8c35d5eeSXin Li<a id="nested-classes-functions-definition"></a>
458*8c35d5eeSXin Li#### 2.6.1 Definition
459*8c35d5eeSXin Li
460*8c35d5eeSXin LiA class can be defined inside of a method, function, or class. A function can be
461*8c35d5eeSXin Lidefined inside a method or function. Nested functions have read-only access to
462*8c35d5eeSXin Livariables defined in enclosing scopes.
463*8c35d5eeSXin Li
464*8c35d5eeSXin Li<a id="s2.6.2-pros"></a>
465*8c35d5eeSXin Li<a id="262-pros"></a>
466*8c35d5eeSXin Li
467*8c35d5eeSXin Li<a id="nested-classes-functions-pros"></a>
468*8c35d5eeSXin Li#### 2.6.2 Pros
469*8c35d5eeSXin Li
470*8c35d5eeSXin LiAllows definition of utility classes and functions that are only used inside of
471*8c35d5eeSXin Lia very limited scope. Very
472*8c35d5eeSXin Li[ADT](http://www.google.com/url?sa=D&q=http://en.wikipedia.org/wiki/Abstract_data_type)-y.
473*8c35d5eeSXin LiCommonly used for implementing decorators.
474*8c35d5eeSXin Li
475*8c35d5eeSXin Li<a id="s2.6.3-cons"></a>
476*8c35d5eeSXin Li<a id="263-cons"></a>
477*8c35d5eeSXin Li
478*8c35d5eeSXin Li<a id="nested-classes-functions-cons"></a>
479*8c35d5eeSXin Li#### 2.6.3 Cons
480*8c35d5eeSXin Li
481*8c35d5eeSXin LiInstances of nested or local classes cannot be pickled. Nested functions and
482*8c35d5eeSXin Liclasses cannot be directly tested. Nesting can make your outer function longer
483*8c35d5eeSXin Liand less readable.
484*8c35d5eeSXin Li
485*8c35d5eeSXin Li<a id="s2.6.4-decision"></a>
486*8c35d5eeSXin Li<a id="264-decision"></a>
487*8c35d5eeSXin Li
488*8c35d5eeSXin Li<a id="nested-classes-functions-decision"></a>
489*8c35d5eeSXin Li#### 2.6.4 Decision
490*8c35d5eeSXin Li
491*8c35d5eeSXin LiThey are fine with some caveats. Avoid nested functions or classes except when
492*8c35d5eeSXin Liclosing over a local value. Do not nest a function just to hide it from users
493*8c35d5eeSXin Liof a module. Instead, prefix its name with an \_ at the module level so that it
494*8c35d5eeSXin Lican still be accessed by tests.
495*8c35d5eeSXin Li
496*8c35d5eeSXin Li<a id="s2.7-list_comprehensions"></a>
497*8c35d5eeSXin Li<a id="27-list_comprehensions"></a>
498*8c35d5eeSXin Li<a id="list_comprehensions"></a>
499*8c35d5eeSXin Li<a id="list-comprehensions"></a>
500*8c35d5eeSXin Li
501*8c35d5eeSXin Li<a id="comprehensions"></a>
502*8c35d5eeSXin Li### 2.7 Comprehensions & Generator Expressions
503*8c35d5eeSXin Li
504*8c35d5eeSXin LiOkay to use for simple cases.
505*8c35d5eeSXin Li
506*8c35d5eeSXin Li<a id="s2.7.1-definition"></a>
507*8c35d5eeSXin Li<a id="271-definition"></a>
508*8c35d5eeSXin Li
509*8c35d5eeSXin Li<a id="comprehensions-definition"></a>
510*8c35d5eeSXin Li#### 2.7.1 Definition
511*8c35d5eeSXin Li
512*8c35d5eeSXin LiList, Dict, and Set comprehensions as well as generator expressions provide a
513*8c35d5eeSXin Liconcise and efficient way to create container types and iterators without
514*8c35d5eeSXin Liresorting to the use of traditional loops, `map()`, `filter()`, or `lambda`.
515*8c35d5eeSXin Li
516*8c35d5eeSXin Li<a id="s2.7.2-pros"></a>
517*8c35d5eeSXin Li<a id="272-pros"></a>
518*8c35d5eeSXin Li
519*8c35d5eeSXin Li<a id="comprehensions-pros"></a>
520*8c35d5eeSXin Li#### 2.7.2 Pros
521*8c35d5eeSXin Li
522*8c35d5eeSXin LiSimple comprehensions can be clearer and simpler than other dict, list, or set
523*8c35d5eeSXin Licreation techniques. Generator expressions can be very efficient, since they
524*8c35d5eeSXin Liavoid the creation of a list entirely.
525*8c35d5eeSXin Li
526*8c35d5eeSXin Li<a id="s2.7.3-cons"></a>
527*8c35d5eeSXin Li<a id="273-cons"></a>
528*8c35d5eeSXin Li
529*8c35d5eeSXin Li<a id="comprehensions-cons"></a>
530*8c35d5eeSXin Li#### 2.7.3 Cons
531*8c35d5eeSXin Li
532*8c35d5eeSXin LiComplicated comprehensions or generator expressions can be hard to read.
533*8c35d5eeSXin Li
534*8c35d5eeSXin Li<a id="s2.7.4-decision"></a>
535*8c35d5eeSXin Li<a id="274-decision"></a>
536*8c35d5eeSXin Li
537*8c35d5eeSXin Li<a id="comprehensions-decision"></a>
538*8c35d5eeSXin Li#### 2.7.4 Decision
539*8c35d5eeSXin Li
540*8c35d5eeSXin LiOkay to use for simple cases. Each portion must fit on one line: mapping
541*8c35d5eeSXin Liexpression, `for` clause, filter expression. Multiple `for` clauses or filter
542*8c35d5eeSXin Liexpressions are not permitted. Use loops instead when things get more
543*8c35d5eeSXin Licomplicated.
544*8c35d5eeSXin Li
545*8c35d5eeSXin Li```python
546*8c35d5eeSXin LiYes:
547*8c35d5eeSXin Li  result = [mapping_expr for value in iterable if filter_expr]
548*8c35d5eeSXin Li
549*8c35d5eeSXin Li  result = [{'key': value} for value in iterable
550*8c35d5eeSXin Li            if a_long_filter_expression(value)]
551*8c35d5eeSXin Li
552*8c35d5eeSXin Li  result = [complicated_transform(x)
553*8c35d5eeSXin Li            for x in iterable if predicate(x)]
554*8c35d5eeSXin Li
555*8c35d5eeSXin Li  descriptive_name = [
556*8c35d5eeSXin Li      transform({'key': key, 'value': value}, color='black')
557*8c35d5eeSXin Li      for key, value in generate_iterable(some_input)
558*8c35d5eeSXin Li      if complicated_condition_is_met(key, value)
559*8c35d5eeSXin Li  ]
560*8c35d5eeSXin Li
561*8c35d5eeSXin Li  result = []
562*8c35d5eeSXin Li  for x in range(10):
563*8c35d5eeSXin Li      for y in range(5):
564*8c35d5eeSXin Li          if x * y > 10:
565*8c35d5eeSXin Li              result.append((x, y))
566*8c35d5eeSXin Li
567*8c35d5eeSXin Li  return {x: complicated_transform(x)
568*8c35d5eeSXin Li          for x in long_generator_function(parameter)
569*8c35d5eeSXin Li          if x is not None}
570*8c35d5eeSXin Li
571*8c35d5eeSXin Li  squares_generator = (x**2 for x in range(10))
572*8c35d5eeSXin Li
573*8c35d5eeSXin Li  unique_names = {user.name for user in users if user is not None}
574*8c35d5eeSXin Li
575*8c35d5eeSXin Li  eat(jelly_bean for jelly_bean in jelly_beans
576*8c35d5eeSXin Li      if jelly_bean.color == 'black')
577*8c35d5eeSXin Li```
578*8c35d5eeSXin Li
579*8c35d5eeSXin Li```python
580*8c35d5eeSXin LiNo:
581*8c35d5eeSXin Li  result = [complicated_transform(
582*8c35d5eeSXin Li                x, some_argument=x+1)
583*8c35d5eeSXin Li            for x in iterable if predicate(x)]
584*8c35d5eeSXin Li
585*8c35d5eeSXin Li  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]
586*8c35d5eeSXin Li
587*8c35d5eeSXin Li  return ((x, y, z)
588*8c35d5eeSXin Li          for x in xrange(5)
589*8c35d5eeSXin Li          for y in xrange(5)
590*8c35d5eeSXin Li          if x != y
591*8c35d5eeSXin Li          for z in xrange(5)
592*8c35d5eeSXin Li          if y != z)
593*8c35d5eeSXin Li```
594*8c35d5eeSXin Li
595*8c35d5eeSXin Li<a id="s2.8-default-iterators-and-operators"></a>
596*8c35d5eeSXin Li
597*8c35d5eeSXin Li<a id="default-iterators-operators"></a>
598*8c35d5eeSXin Li### 2.8 Default Iterators and Operators
599*8c35d5eeSXin Li
600*8c35d5eeSXin LiUse default iterators and operators for types that support them, like lists,
601*8c35d5eeSXin Lidictionaries, and files.
602*8c35d5eeSXin Li
603*8c35d5eeSXin Li<a id="s2.8.1-definition"></a>
604*8c35d5eeSXin Li<a id="281-definition"></a>
605*8c35d5eeSXin Li
606*8c35d5eeSXin Li<a id="default-iterators-operators-definition"></a>
607*8c35d5eeSXin Li#### 2.8.1 Definition
608*8c35d5eeSXin Li
609*8c35d5eeSXin LiContainer types, like dictionaries and lists, define default iterators and
610*8c35d5eeSXin Limembership test operators ("in" and "not in").
611*8c35d5eeSXin Li
612*8c35d5eeSXin Li<a id="s2.8.2-pros"></a>
613*8c35d5eeSXin Li<a id="282-pros"></a>
614*8c35d5eeSXin Li
615*8c35d5eeSXin Li<a id="default-iterators-operators-pros"></a>
616*8c35d5eeSXin Li#### 2.8.2 Pros
617*8c35d5eeSXin Li
618*8c35d5eeSXin LiThe default iterators and operators are simple and efficient. They express the
619*8c35d5eeSXin Lioperation directly, without extra method calls. A function that uses default
620*8c35d5eeSXin Lioperators is generic. It can be used with any type that supports the operation.
621*8c35d5eeSXin Li
622*8c35d5eeSXin Li<a id="s2.8.3-cons"></a>
623*8c35d5eeSXin Li<a id="283-cons"></a>
624*8c35d5eeSXin Li
625*8c35d5eeSXin Li<a id="default-iterators-operators-cons"></a>
626*8c35d5eeSXin Li#### 2.8.3 Cons
627*8c35d5eeSXin Li
628*8c35d5eeSXin LiYou can't tell the type of objects by reading the method names (e.g. has\_key()
629*8c35d5eeSXin Limeans a dictionary). This is also an advantage.
630*8c35d5eeSXin Li
631*8c35d5eeSXin Li<a id="s2.8.4-decision"></a>
632*8c35d5eeSXin Li<a id="284-decision"></a>
633*8c35d5eeSXin Li
634*8c35d5eeSXin Li<a id="default-iterators-operators-decision"></a>
635*8c35d5eeSXin Li#### 2.8.4 Decision
636*8c35d5eeSXin Li
637*8c35d5eeSXin LiUse default iterators and operators for types that support them, like lists,
638*8c35d5eeSXin Lidictionaries, and files. The built-in types define iterator methods, too. Prefer
639*8c35d5eeSXin Lithese methods to methods that return lists, except that you should not mutate a
640*8c35d5eeSXin Licontainer while iterating over it. Never use Python 2 specific iteration
641*8c35d5eeSXin Limethods such as `dict.iter*()` unless necessary.
642*8c35d5eeSXin Li
643*8c35d5eeSXin Li```python
644*8c35d5eeSXin LiYes:  for key in adict: ...
645*8c35d5eeSXin Li      if key not in adict: ...
646*8c35d5eeSXin Li      if obj in alist: ...
647*8c35d5eeSXin Li      for line in afile: ...
648*8c35d5eeSXin Li      for k, v in adict.items(): ...
649*8c35d5eeSXin Li      for k, v in six.iteritems(adict): ...
650*8c35d5eeSXin Li```
651*8c35d5eeSXin Li
652*8c35d5eeSXin Li```python
653*8c35d5eeSXin LiNo:   for key in adict.keys(): ...
654*8c35d5eeSXin Li      if not adict.has_key(key): ...
655*8c35d5eeSXin Li      for line in afile.readlines(): ...
656*8c35d5eeSXin Li      for k, v in dict.iteritems(): ...
657*8c35d5eeSXin Li```
658*8c35d5eeSXin Li
659*8c35d5eeSXin Li<a id="s2.9-generators"></a>
660*8c35d5eeSXin Li<a id="29-generators"></a>
661*8c35d5eeSXin Li
662*8c35d5eeSXin Li<a id="generators"></a>
663*8c35d5eeSXin Li### 2.9 Generators
664*8c35d5eeSXin Li
665*8c35d5eeSXin LiUse generators as needed.
666*8c35d5eeSXin Li
667*8c35d5eeSXin Li<a id="s2.9.1-definition"></a>
668*8c35d5eeSXin Li<a id="291-definition"></a>
669*8c35d5eeSXin Li
670*8c35d5eeSXin Li<a id="generators-definition"></a>
671*8c35d5eeSXin Li#### 2.9 Definition
672*8c35d5eeSXin Li
673*8c35d5eeSXin LiA generator function returns an iterator that yields a value each time it
674*8c35d5eeSXin Liexecutes a yield statement. After it yields a value, the runtime state of the
675*8c35d5eeSXin Ligenerator function is suspended until the next value is needed.
676*8c35d5eeSXin Li
677*8c35d5eeSXin Li<a id="s2.9.2-pros"></a>
678*8c35d5eeSXin Li<a id="292-pros"></a>
679*8c35d5eeSXin Li
680*8c35d5eeSXin Li<a id="generators-pros"></a>
681*8c35d5eeSXin Li#### 2.9.2 Pros
682*8c35d5eeSXin Li
683*8c35d5eeSXin LiSimpler code, because the state of local variables and control flow are
684*8c35d5eeSXin Lipreserved for each call. A generator uses less memory than a function that
685*8c35d5eeSXin Licreates an entire list of values at once.
686*8c35d5eeSXin Li
687*8c35d5eeSXin Li<a id="s2.9.3-cons"></a>
688*8c35d5eeSXin Li<a id="293-cons"></a>
689*8c35d5eeSXin Li
690*8c35d5eeSXin Li<a id="generators-cons"></a>
691*8c35d5eeSXin Li#### 2.9.3 Cons
692*8c35d5eeSXin Li
693*8c35d5eeSXin LiNone.
694*8c35d5eeSXin Li
695*8c35d5eeSXin Li<a id="s2.9.4-decision"></a>
696*8c35d5eeSXin Li<a id="294-decision"></a>
697*8c35d5eeSXin Li
698*8c35d5eeSXin Li<a id="generators-decision"></a>
699*8c35d5eeSXin Li#### 2.9.4 Decision
700*8c35d5eeSXin Li
701*8c35d5eeSXin LiFine. Use "Yields:" rather than "Returns:" in the docstring for generator
702*8c35d5eeSXin Lifunctions.
703*8c35d5eeSXin Li
704*8c35d5eeSXin Li<a id="s2.10-lambda-functions"></a>
705*8c35d5eeSXin Li<a id="210-lambda-functions"></a>
706*8c35d5eeSXin Li
707*8c35d5eeSXin Li<a id="lambdas"></a>
708*8c35d5eeSXin Li### 2.10 Lambda Functions
709*8c35d5eeSXin Li
710*8c35d5eeSXin LiOkay for one-liners.
711*8c35d5eeSXin Li
712*8c35d5eeSXin Li<a id="s2.10.1-definition"></a>
713*8c35d5eeSXin Li<a id="2101-definition"></a>
714*8c35d5eeSXin Li
715*8c35d5eeSXin Li<a id="lambdas-definition"></a>
716*8c35d5eeSXin Li#### 2.10.1 Definition
717*8c35d5eeSXin Li
718*8c35d5eeSXin LiLambdas define anonymous functions in an expression, as opposed to a statement.
719*8c35d5eeSXin LiThey are often used to define callbacks or operators for higher-order functions
720*8c35d5eeSXin Lilike `map()` and `filter()`.
721*8c35d5eeSXin Li
722*8c35d5eeSXin Li<a id="s2.10.2-pros"></a>
723*8c35d5eeSXin Li<a id="2102-pros"></a>
724*8c35d5eeSXin Li
725*8c35d5eeSXin Li<a id="lambdas-pros"></a>
726*8c35d5eeSXin Li#### 2.10.2 Pros
727*8c35d5eeSXin Li
728*8c35d5eeSXin LiConvenient.
729*8c35d5eeSXin Li
730*8c35d5eeSXin Li<a id="s2.10.3-cons"></a>
731*8c35d5eeSXin Li<a id="2103-cons"></a>
732*8c35d5eeSXin Li
733*8c35d5eeSXin Li<a id="lambdas-cons"></a>
734*8c35d5eeSXin Li#### 2.10.3 Cons
735*8c35d5eeSXin Li
736*8c35d5eeSXin LiHarder to read and debug than local functions. The lack of names means stack
737*8c35d5eeSXin Litraces are more difficult to understand. Expressiveness is limited because the
738*8c35d5eeSXin Lifunction may only contain an expression.
739*8c35d5eeSXin Li
740*8c35d5eeSXin Li<a id="s2.10.4-decision"></a>
741*8c35d5eeSXin Li<a id="2104-decision"></a>
742*8c35d5eeSXin Li
743*8c35d5eeSXin Li<a id="lambdas-decision"></a>
744*8c35d5eeSXin Li#### 2.10.4 Decision
745*8c35d5eeSXin Li
746*8c35d5eeSXin LiOkay to use them for one-liners. If the code inside the lambda function is
747*8c35d5eeSXin Lilonger than 60-80 chars, it's probably better to define it as a regular [nested
748*8c35d5eeSXin Lifunction](#lexical-scoping).
749*8c35d5eeSXin Li
750*8c35d5eeSXin LiFor common operations like multiplication, use the functions from the `operator`
751*8c35d5eeSXin Limodule instead of lambda functions. For example, prefer `operator.mul` to
752*8c35d5eeSXin Li`lambda x, y: x * y`.
753*8c35d5eeSXin Li
754*8c35d5eeSXin Li<a id="s2.11-conditional-expressions"></a>
755*8c35d5eeSXin Li<a id="211-conditional-expressions"></a>
756*8c35d5eeSXin Li
757*8c35d5eeSXin Li<a id="conditional-expressions"></a>
758*8c35d5eeSXin Li### 2.11 Conditional Expressions
759*8c35d5eeSXin Li
760*8c35d5eeSXin LiOkay for simple cases.
761*8c35d5eeSXin Li
762*8c35d5eeSXin Li<a id="s2.11.1-definition"></a>
763*8c35d5eeSXin Li<a id="2111-definition"></a>
764*8c35d5eeSXin Li
765*8c35d5eeSXin Li<a id="conditional-expressions-definition"></a>
766*8c35d5eeSXin Li#### 2.11.1 Definition
767*8c35d5eeSXin Li
768*8c35d5eeSXin LiConditional expressions (sometimes called a “ternary operator”) are mechanisms
769*8c35d5eeSXin Lithat provide a shorter syntax for if statements. For example:
770*8c35d5eeSXin Li`x = 1 if cond else 2`.
771*8c35d5eeSXin Li
772*8c35d5eeSXin Li<a id="s2.11.2-pros"></a>
773*8c35d5eeSXin Li<a id="2112-pros"></a>
774*8c35d5eeSXin Li
775*8c35d5eeSXin Li<a id="conditional-expressions-pros"></a>
776*8c35d5eeSXin Li#### 2.11.2 Pros
777*8c35d5eeSXin Li
778*8c35d5eeSXin LiShorter and more convenient than an if statement.
779*8c35d5eeSXin Li
780*8c35d5eeSXin Li<a id="s2.11.3-cons"></a>
781*8c35d5eeSXin Li<a id="2113-cons"></a>
782*8c35d5eeSXin Li
783*8c35d5eeSXin Li<a id="conditional-expressions-cons"></a>
784*8c35d5eeSXin Li#### 2.11.3 Cons
785*8c35d5eeSXin Li
786*8c35d5eeSXin LiMay be harder to read than an if statement. The condition may be difficult to
787*8c35d5eeSXin Lilocate if the expression is long.
788*8c35d5eeSXin Li
789*8c35d5eeSXin Li<a id="s2.11.4-decision"></a>
790*8c35d5eeSXin Li<a id="2114-decision"></a>
791*8c35d5eeSXin Li
792*8c35d5eeSXin Li<a id="conditional-expressions-decision"></a>
793*8c35d5eeSXin Li#### 2.11.4 Decision
794*8c35d5eeSXin Li
795*8c35d5eeSXin LiOkay to use for simple cases. Each portion must fit on one line:
796*8c35d5eeSXin Litrue-expression, if-expression, else-expression. Use a complete if statement
797*8c35d5eeSXin Liwhen things get more complicated.
798*8c35d5eeSXin Li
799*8c35d5eeSXin Li```python
800*8c35d5eeSXin Lione_line = 'yes' if predicate(value) else 'no'
801*8c35d5eeSXin Lislightly_split = ('yes' if predicate(value)
802*8c35d5eeSXin Li                  else 'no, nein, nyet')
803*8c35d5eeSXin Lithe_longest_ternary_style_that_can_be_done = (
804*8c35d5eeSXin Li    'yes, true, affirmative, confirmed, correct'
805*8c35d5eeSXin Li    if predicate(value)
806*8c35d5eeSXin Li    else 'no, false, negative, nay')
807*8c35d5eeSXin Li```
808*8c35d5eeSXin Li
809*8c35d5eeSXin Li```python
810*8c35d5eeSXin Libad_line_breaking = ('yes' if predicate(value) else
811*8c35d5eeSXin Li                     'no')
812*8c35d5eeSXin Liportion_too_long = ('yes'
813*8c35d5eeSXin Li                    if some_long_module.some_long_predicate_function(
814*8c35d5eeSXin Li                        really_long_variable_name)
815*8c35d5eeSXin Li                    else 'no, false, negative, nay')
816*8c35d5eeSXin Li```
817*8c35d5eeSXin Li
818*8c35d5eeSXin Li<a id="s2.12-default-argument-values"></a>
819*8c35d5eeSXin Li<a id="212-default-argument-values"></a>
820*8c35d5eeSXin Li
821*8c35d5eeSXin Li<a id="default-arguments"></a>
822*8c35d5eeSXin Li### 2.12 Default Argument Values
823*8c35d5eeSXin Li
824*8c35d5eeSXin LiOkay in most cases.
825*8c35d5eeSXin Li
826*8c35d5eeSXin Li<a id="s2.12.1-definition"></a>
827*8c35d5eeSXin Li<a id="2121-definition"></a>
828*8c35d5eeSXin Li
829*8c35d5eeSXin Li<a id="default-arguments-definition"></a>
830*8c35d5eeSXin Li#### 2.12.1 Definition
831*8c35d5eeSXin Li
832*8c35d5eeSXin LiYou can specify values for variables at the end of a function's parameter list,
833*8c35d5eeSXin Lie.g., `def foo(a, b=0):`.  If `foo` is called with only one argument,
834*8c35d5eeSXin Li`b` is set to 0. If it is called with two arguments, `b` has the value of the
835*8c35d5eeSXin Lisecond argument.
836*8c35d5eeSXin Li
837*8c35d5eeSXin Li<a id="s2.12.2-pros"></a>
838*8c35d5eeSXin Li<a id="2122-pros"></a>
839*8c35d5eeSXin Li
840*8c35d5eeSXin Li<a id="default-arguments-pros"></a>
841*8c35d5eeSXin Li#### 2.12.2 Pros
842*8c35d5eeSXin Li
843*8c35d5eeSXin LiOften you have a function that uses lots of default values, but on rare
844*8c35d5eeSXin Lioccasions you want to override the defaults. Default argument values provide an
845*8c35d5eeSXin Lieasy way to do this, without having to define lots of functions for the rare
846*8c35d5eeSXin Liexceptions. As Python does not support overloaded methods/functions, default
847*8c35d5eeSXin Liarguments are an easy way of "faking" the overloading behavior.
848*8c35d5eeSXin Li
849*8c35d5eeSXin Li<a id="s2.12.3-cons"></a>
850*8c35d5eeSXin Li<a id="2123-cons"></a>
851*8c35d5eeSXin Li
852*8c35d5eeSXin Li<a id="default-arguments-cons"></a>
853*8c35d5eeSXin Li#### 2.12.3 Cons
854*8c35d5eeSXin Li
855*8c35d5eeSXin LiDefault arguments are evaluated once at module load time. This may cause
856*8c35d5eeSXin Liproblems if the argument is a mutable object such as a list or a dictionary. If
857*8c35d5eeSXin Lithe function modifies the object (e.g., by appending an item to a list), the
858*8c35d5eeSXin Lidefault value is modified.
859*8c35d5eeSXin Li
860*8c35d5eeSXin Li<a id="s2.12.4-decision"></a>
861*8c35d5eeSXin Li<a id="2124-decision"></a>
862*8c35d5eeSXin Li
863*8c35d5eeSXin Li<a id="default-arguments-decision"></a>
864*8c35d5eeSXin Li#### 2.12.4 Decision
865*8c35d5eeSXin Li
866*8c35d5eeSXin LiOkay to use with the following caveat:
867*8c35d5eeSXin Li
868*8c35d5eeSXin LiDo not use mutable objects as default values in the function or method
869*8c35d5eeSXin Lidefinition.
870*8c35d5eeSXin Li
871*8c35d5eeSXin Li```python
872*8c35d5eeSXin LiYes: def foo(a, b=None):
873*8c35d5eeSXin Li         if b is None:
874*8c35d5eeSXin Li             b = []
875*8c35d5eeSXin LiYes: def foo(a, b: Optional[Sequence] = None):
876*8c35d5eeSXin Li         if b is None:
877*8c35d5eeSXin Li             b = []
878*8c35d5eeSXin LiYes: def foo(a, b: Sequence = ()):  # Empty tuple OK since tuples are immutable
879*8c35d5eeSXin Li         ...
880*8c35d5eeSXin Li```
881*8c35d5eeSXin Li
882*8c35d5eeSXin Li```python
883*8c35d5eeSXin LiNo:  def foo(a, b=[]):
884*8c35d5eeSXin Li         ...
885*8c35d5eeSXin LiNo:  def foo(a, b=time.time()):  # The time the module was loaded???
886*8c35d5eeSXin Li         ...
887*8c35d5eeSXin LiNo:  def foo(a, b=FLAGS.my_thing):  # sys.argv has not yet been parsed...
888*8c35d5eeSXin Li         ...
889*8c35d5eeSXin Li```
890*8c35d5eeSXin Li
891*8c35d5eeSXin Li<a id="s2.13-properties"></a>
892*8c35d5eeSXin Li<a id="213-properties"></a>
893*8c35d5eeSXin Li
894*8c35d5eeSXin Li<a id="properties"></a>
895*8c35d5eeSXin Li### 2.13 Properties
896*8c35d5eeSXin Li
897*8c35d5eeSXin LiUse properties for accessing or setting data where you would normally have used
898*8c35d5eeSXin Lisimple, lightweight accessor or setter methods.
899*8c35d5eeSXin Li
900*8c35d5eeSXin Li<a id="s2.13.1-definition"></a>
901*8c35d5eeSXin Li<a id="2131-definition"></a>
902*8c35d5eeSXin Li
903*8c35d5eeSXin Li<a id="properties-definition"></a>
904*8c35d5eeSXin Li#### 2.13.1 Definition
905*8c35d5eeSXin Li
906*8c35d5eeSXin LiA way to wrap method calls for getting and setting an attribute as a standard
907*8c35d5eeSXin Liattribute access when the computation is lightweight.
908*8c35d5eeSXin Li
909*8c35d5eeSXin Li<a id="s2.13.2-pros"></a>
910*8c35d5eeSXin Li<a id="2132-pros"></a>
911*8c35d5eeSXin Li
912*8c35d5eeSXin Li<a id="properties-pros"></a>
913*8c35d5eeSXin Li#### 2.13.2 Pros
914*8c35d5eeSXin Li
915*8c35d5eeSXin LiReadability is increased by eliminating explicit get and set method calls for
916*8c35d5eeSXin Lisimple attribute access. Allows calculations to be lazy. Considered the Pythonic
917*8c35d5eeSXin Liway to maintain the interface of a class. In terms of performance, allowing
918*8c35d5eeSXin Liproperties bypasses needing trivial accessor methods when a direct variable
919*8c35d5eeSXin Liaccess is reasonable. This also allows accessor methods to be added in the
920*8c35d5eeSXin Lifuture without breaking the interface.
921*8c35d5eeSXin Li
922*8c35d5eeSXin Li<a id="s2.13.3-cons"></a>
923*8c35d5eeSXin Li<a id="2133-cons"></a>
924*8c35d5eeSXin Li
925*8c35d5eeSXin Li<a id="properties-cons"></a>
926*8c35d5eeSXin Li#### 2.13.3 Cons
927*8c35d5eeSXin Li
928*8c35d5eeSXin LiMust inherit from `object` in Python 2. Can hide side-effects much like operator
929*8c35d5eeSXin Lioverloading. Can be confusing for subclasses.
930*8c35d5eeSXin Li
931*8c35d5eeSXin Li<a id="s2.13.4-decision"></a>
932*8c35d5eeSXin Li<a id="2134-decision"></a>
933*8c35d5eeSXin Li
934*8c35d5eeSXin Li<a id="properties-decision"></a>
935*8c35d5eeSXin Li#### 2.13.4 Decision
936*8c35d5eeSXin Li
937*8c35d5eeSXin LiUse properties in new code to access or set data where you would normally have
938*8c35d5eeSXin Liused simple, lightweight accessor or setter methods. Properties should be
939*8c35d5eeSXin Licreated with the `@property` [decorator](#s2.17-function-and-method-decorators).
940*8c35d5eeSXin Li
941*8c35d5eeSXin LiInheritance with properties can be non-obvious if the property itself is not
942*8c35d5eeSXin Lioverridden. Thus one must make sure that accessor methods are called indirectly
943*8c35d5eeSXin Lito ensure methods overridden in subclasses are called by the property (using the
944*8c35d5eeSXin LiTemplate Method DP).
945*8c35d5eeSXin Li
946*8c35d5eeSXin Li```python
947*8c35d5eeSXin LiYes: import math
948*8c35d5eeSXin Li
949*8c35d5eeSXin Li     class Square(object):
950*8c35d5eeSXin Li         """A square with two properties: a writable area and a read-only perimeter.
951*8c35d5eeSXin Li
952*8c35d5eeSXin Li         To use:
953*8c35d5eeSXin Li         >>> sq = Square(3)
954*8c35d5eeSXin Li         >>> sq.area
955*8c35d5eeSXin Li         9
956*8c35d5eeSXin Li         >>> sq.perimeter
957*8c35d5eeSXin Li         12
958*8c35d5eeSXin Li         >>> sq.area = 16
959*8c35d5eeSXin Li         >>> sq.side
960*8c35d5eeSXin Li         4
961*8c35d5eeSXin Li         >>> sq.perimeter
962*8c35d5eeSXin Li         16
963*8c35d5eeSXin Li         """
964*8c35d5eeSXin Li
965*8c35d5eeSXin Li         def __init__(self, side):
966*8c35d5eeSXin Li             self.side = side
967*8c35d5eeSXin Li
968*8c35d5eeSXin Li         @property
969*8c35d5eeSXin Li         def area(self):
970*8c35d5eeSXin Li             """Area of the square."""
971*8c35d5eeSXin Li             return self._get_area()
972*8c35d5eeSXin Li
973*8c35d5eeSXin Li         @area.setter
974*8c35d5eeSXin Li         def area(self, area):
975*8c35d5eeSXin Li             return self._set_area(area)
976*8c35d5eeSXin Li
977*8c35d5eeSXin Li         def _get_area(self):
978*8c35d5eeSXin Li             """Indirect accessor to calculate the 'area' property."""
979*8c35d5eeSXin Li             return self.side ** 2
980*8c35d5eeSXin Li
981*8c35d5eeSXin Li         def _set_area(self, area):
982*8c35d5eeSXin Li             """Indirect setter to set the 'area' property."""
983*8c35d5eeSXin Li             self.side = math.sqrt(area)
984*8c35d5eeSXin Li
985*8c35d5eeSXin Li         @property
986*8c35d5eeSXin Li         def perimeter(self):
987*8c35d5eeSXin Li             return self.side * 4
988*8c35d5eeSXin Li```
989*8c35d5eeSXin Li
990*8c35d5eeSXin Li<a id="s2.14-truefalse-evaluations"></a>
991*8c35d5eeSXin Li<a id="214-truefalse-evaluations"></a>
992*8c35d5eeSXin Li
993*8c35d5eeSXin Li<a id="truefalse-evaluations"></a>
994*8c35d5eeSXin Li### 2.14 True/False Evaluations
995*8c35d5eeSXin Li
996*8c35d5eeSXin LiUse the "implicit" false if at all possible.
997*8c35d5eeSXin Li
998*8c35d5eeSXin Li<a id="s2.14.1-definition"></a>
999*8c35d5eeSXin Li<a id="2141-definition"></a>
1000*8c35d5eeSXin Li
1001*8c35d5eeSXin Li<a id="truefalse-evaluations-definition"></a>
1002*8c35d5eeSXin Li#### 2.14.1 Definition
1003*8c35d5eeSXin Li
1004*8c35d5eeSXin LiPython evaluates certain values as `False` when in a boolean context. A quick
1005*8c35d5eeSXin Li"rule of thumb" is that all "empty" values are considered false, so
1006*8c35d5eeSXin Li`0, None, [], {}, ''` all evaluate as false in a boolean context.
1007*8c35d5eeSXin Li
1008*8c35d5eeSXin Li<a id="s2.14.2-pros"></a>
1009*8c35d5eeSXin Li<a id="2142-pros"></a>
1010*8c35d5eeSXin Li
1011*8c35d5eeSXin Li<a id="truefalse-evaluations-pros"></a>
1012*8c35d5eeSXin Li#### 2.14.2 Pros
1013*8c35d5eeSXin Li
1014*8c35d5eeSXin LiConditions using Python booleans are easier to read and less error-prone. In
1015*8c35d5eeSXin Limost cases, they're also faster.
1016*8c35d5eeSXin Li
1017*8c35d5eeSXin Li<a id="s2.14.3-cons"></a>
1018*8c35d5eeSXin Li<a id="2143-cons"></a>
1019*8c35d5eeSXin Li
1020*8c35d5eeSXin Li<a id="truefalse-evaluations-cons"></a>
1021*8c35d5eeSXin Li#### 2.14.3 Cons
1022*8c35d5eeSXin Li
1023*8c35d5eeSXin LiMay look strange to C/C++ developers.
1024*8c35d5eeSXin Li
1025*8c35d5eeSXin Li<a id="s2.14.4-decision"></a>
1026*8c35d5eeSXin Li<a id="2144-decision"></a>
1027*8c35d5eeSXin Li
1028*8c35d5eeSXin Li<a id="truefalse-evaluations-decision"></a>
1029*8c35d5eeSXin Li#### 2.14.4 Decision
1030*8c35d5eeSXin Li
1031*8c35d5eeSXin LiUse the "implicit" false if possible, e.g., `if foo:` rather than `if foo !=
1032*8c35d5eeSXin Li[]:`. There are a few caveats that you should keep in mind though:
1033*8c35d5eeSXin Li
1034*8c35d5eeSXin Li-   Always use `if foo is None:` (or `is not None`) to check for a `None`
1035*8c35d5eeSXin Li    value-e.g., when testing whether a variable or argument that defaults to
1036*8c35d5eeSXin Li    `None` was set to some other value. The other value might be a value that's
1037*8c35d5eeSXin Li    false in a boolean context!
1038*8c35d5eeSXin Li
1039*8c35d5eeSXin Li-   Never compare a boolean variable to `False` using `==`. Use `if not x:`
1040*8c35d5eeSXin Li    instead. If you need to distinguish `False` from `None` then chain the
1041*8c35d5eeSXin Li    expressions, such as `if not x and x is not None:`.
1042*8c35d5eeSXin Li
1043*8c35d5eeSXin Li-   For sequences (strings, lists, tuples), use the fact that empty sequences
1044*8c35d5eeSXin Li    are false, so `if seq:` and `if not seq:` are preferable to `if len(seq):`
1045*8c35d5eeSXin Li    and `if not len(seq):` respectively.
1046*8c35d5eeSXin Li
1047*8c35d5eeSXin Li-   When handling integers, implicit false may involve more risk than benefit
1048*8c35d5eeSXin Li    (i.e., accidentally handling `None` as 0). You may compare a value which is
1049*8c35d5eeSXin Li    known to be an integer (and is not the result of `len()`) against the
1050*8c35d5eeSXin Li    integer 0.
1051*8c35d5eeSXin Li
1052*8c35d5eeSXin Li    ```python
1053*8c35d5eeSXin Li    Yes: if not users:
1054*8c35d5eeSXin Li             print('no users')
1055*8c35d5eeSXin Li
1056*8c35d5eeSXin Li         if foo == 0:
1057*8c35d5eeSXin Li             self.handle_zero()
1058*8c35d5eeSXin Li
1059*8c35d5eeSXin Li         if i % 10 == 0:
1060*8c35d5eeSXin Li             self.handle_multiple_of_ten()
1061*8c35d5eeSXin Li
1062*8c35d5eeSXin Li         def f(x=None):
1063*8c35d5eeSXin Li             if x is None:
1064*8c35d5eeSXin Li                 x = []
1065*8c35d5eeSXin Li    ```
1066*8c35d5eeSXin Li
1067*8c35d5eeSXin Li    ```python
1068*8c35d5eeSXin Li    No:  if len(users) == 0:
1069*8c35d5eeSXin Li             print('no users')
1070*8c35d5eeSXin Li
1071*8c35d5eeSXin Li         if foo is not None and not foo:
1072*8c35d5eeSXin Li             self.handle_zero()
1073*8c35d5eeSXin Li
1074*8c35d5eeSXin Li         if not i % 10:
1075*8c35d5eeSXin Li             self.handle_multiple_of_ten()
1076*8c35d5eeSXin Li
1077*8c35d5eeSXin Li         def f(x=None):
1078*8c35d5eeSXin Li             x = x or []
1079*8c35d5eeSXin Li    ```
1080*8c35d5eeSXin Li
1081*8c35d5eeSXin Li-   Note that `'0'` (i.e., `0` as string) evaluates to true.
1082*8c35d5eeSXin Li
1083*8c35d5eeSXin Li<a id="s2.15-deprecated-language-features"></a>
1084*8c35d5eeSXin Li<a id="215-deprecated-language-features"></a>
1085*8c35d5eeSXin Li
1086*8c35d5eeSXin Li<a id="deprecated-features"></a>
1087*8c35d5eeSXin Li### 2.15 Deprecated Language Features
1088*8c35d5eeSXin Li
1089*8c35d5eeSXin LiUse string methods instead of the `string` module where possible. Use function
1090*8c35d5eeSXin Licall syntax instead of `apply`. Use list comprehensions and `for` loops instead
1091*8c35d5eeSXin Liof `filter` and `map` when the function argument would have been an inlined
1092*8c35d5eeSXin Lilambda anyway. Use `for` loops instead of `reduce`.
1093*8c35d5eeSXin Li
1094*8c35d5eeSXin Li<a id="s2.15.1-definition"></a>
1095*8c35d5eeSXin Li<a id="2151-definition"></a>
1096*8c35d5eeSXin Li
1097*8c35d5eeSXin Li<a id="deprecated-features-definition"></a>
1098*8c35d5eeSXin Li#### 2.15.1 Definition
1099*8c35d5eeSXin Li
1100*8c35d5eeSXin LiCurrent versions of Python provide alternative constructs that people find
1101*8c35d5eeSXin Ligenerally preferable.
1102*8c35d5eeSXin Li
1103*8c35d5eeSXin Li<a id="s2.15.2-decision"></a>
1104*8c35d5eeSXin Li<a id="2152-decision"></a>
1105*8c35d5eeSXin Li
1106*8c35d5eeSXin Li<a id="deprecated-features-decision"></a>
1107*8c35d5eeSXin Li#### 2.15.2 Decision
1108*8c35d5eeSXin Li
1109*8c35d5eeSXin LiWe do not use any Python version which does not support these features, so there
1110*8c35d5eeSXin Liis no reason not to use the new styles.
1111*8c35d5eeSXin Li
1112*8c35d5eeSXin Li```python
1113*8c35d5eeSXin LiYes: words = foo.split(':')
1114*8c35d5eeSXin Li
1115*8c35d5eeSXin Li     [x[1] for x in my_list if x[2] == 5]
1116*8c35d5eeSXin Li
1117*8c35d5eeSXin Li     map(math.sqrt, data)    # Ok. No inlined lambda expression.
1118*8c35d5eeSXin Li
1119*8c35d5eeSXin Li     fn(*args, **kwargs)
1120*8c35d5eeSXin Li```
1121*8c35d5eeSXin Li
1122*8c35d5eeSXin Li```python
1123*8c35d5eeSXin LiNo:  words = string.split(foo, ':')
1124*8c35d5eeSXin Li
1125*8c35d5eeSXin Li     map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
1126*8c35d5eeSXin Li
1127*8c35d5eeSXin Li     apply(fn, args, kwargs)
1128*8c35d5eeSXin Li```
1129*8c35d5eeSXin Li
1130*8c35d5eeSXin Li<a id="s2.16-lexical-scoping"></a>
1131*8c35d5eeSXin Li<a id="216-lexical-scoping"></a>
1132*8c35d5eeSXin Li
1133*8c35d5eeSXin Li<a id="lexical-scoping"></a>
1134*8c35d5eeSXin Li### 2.16 Lexical Scoping
1135*8c35d5eeSXin Li
1136*8c35d5eeSXin LiOkay to use.
1137*8c35d5eeSXin Li
1138*8c35d5eeSXin Li<a id="s2.16.1-definition"></a>
1139*8c35d5eeSXin Li<a id="2161-definition"></a>
1140*8c35d5eeSXin Li
1141*8c35d5eeSXin Li<a id="lexical-scoping-definition"></a>
1142*8c35d5eeSXin Li#### 2.16.1 Definition
1143*8c35d5eeSXin Li
1144*8c35d5eeSXin LiA nested Python function can refer to variables defined in enclosing functions,
1145*8c35d5eeSXin Libut can not assign to them. Variable bindings are resolved using lexical
1146*8c35d5eeSXin Liscoping, that is, based on the static program text. Any assignment to a name in
1147*8c35d5eeSXin Lia block will cause Python to treat all references to that name as a local
1148*8c35d5eeSXin Livariable, even if the use precedes the assignment. If a global declaration
1149*8c35d5eeSXin Lioccurs, the name is treated as a global variable.
1150*8c35d5eeSXin Li
1151*8c35d5eeSXin LiAn example of the use of this feature is:
1152*8c35d5eeSXin Li
1153*8c35d5eeSXin Li```python
1154*8c35d5eeSXin Lidef get_adder(summand1):
1155*8c35d5eeSXin Li    """Returns a function that adds numbers to a given number."""
1156*8c35d5eeSXin Li    def adder(summand2):
1157*8c35d5eeSXin Li        return summand1 + summand2
1158*8c35d5eeSXin Li
1159*8c35d5eeSXin Li    return adder
1160*8c35d5eeSXin Li```
1161*8c35d5eeSXin Li
1162*8c35d5eeSXin Li<a id="s2.16.2-pros"></a>
1163*8c35d5eeSXin Li<a id="2162-pros"></a>
1164*8c35d5eeSXin Li
1165*8c35d5eeSXin Li<a id="lexical-scoping-pros"></a>
1166*8c35d5eeSXin Li#### 2.16.2 Pros
1167*8c35d5eeSXin Li
1168*8c35d5eeSXin LiOften results in clearer, more elegant code. Especially comforting to
1169*8c35d5eeSXin Liexperienced Lisp and Scheme (and Haskell and ML and ...) programmers.
1170*8c35d5eeSXin Li
1171*8c35d5eeSXin Li<a id="s2.16.3-cons"></a>
1172*8c35d5eeSXin Li<a id="2163-cons"></a>
1173*8c35d5eeSXin Li
1174*8c35d5eeSXin Li<a id="lexical-scoping-cons"></a>
1175*8c35d5eeSXin Li#### 2.16.3 Cons
1176*8c35d5eeSXin Li
1177*8c35d5eeSXin LiCan lead to confusing bugs. Such as this example based on
1178*8c35d5eeSXin Li[PEP-0227](http://www.google.com/url?sa=D&q=http://www.python.org/dev/peps/pep-0227/):
1179*8c35d5eeSXin Li
1180*8c35d5eeSXin Li```python
1181*8c35d5eeSXin Lii = 4
1182*8c35d5eeSXin Lidef foo(x):
1183*8c35d5eeSXin Li    def bar():
1184*8c35d5eeSXin Li        print(i, end='')
1185*8c35d5eeSXin Li    # ...
1186*8c35d5eeSXin Li    # A bunch of code here
1187*8c35d5eeSXin Li    # ...
1188*8c35d5eeSXin Li    for i in x:  # Ah, i *is* local to foo, so this is what bar sees
1189*8c35d5eeSXin Li        print(i, end='')
1190*8c35d5eeSXin Li    bar()
1191*8c35d5eeSXin Li```
1192*8c35d5eeSXin Li
1193*8c35d5eeSXin LiSo `foo([1, 2, 3])` will print `1 2 3 3`, not `1 2 3
1194*8c35d5eeSXin Li4`.
1195*8c35d5eeSXin Li
1196*8c35d5eeSXin Li<a id="s2.16.4-decision"></a>
1197*8c35d5eeSXin Li<a id="2164-decision"></a>
1198*8c35d5eeSXin Li
1199*8c35d5eeSXin Li<a id="lexical-scoping-decision"></a>
1200*8c35d5eeSXin Li#### 2.16.4 Decision
1201*8c35d5eeSXin Li
1202*8c35d5eeSXin LiOkay to use.
1203*8c35d5eeSXin Li
1204*8c35d5eeSXin Li<a id="s2.17-function-and-method-decorators"></a>
1205*8c35d5eeSXin Li<a id="217-function-and-method-decorators"></a>
1206*8c35d5eeSXin Li<a id="function-and-method-decorators"></a>
1207*8c35d5eeSXin Li
1208*8c35d5eeSXin Li<a id="decorators"></a>
1209*8c35d5eeSXin Li### 2.17 Function and Method Decorators
1210*8c35d5eeSXin Li
1211*8c35d5eeSXin LiUse decorators judiciously when there is a clear advantage. Avoid
1212*8c35d5eeSXin Li`@staticmethod` and limit use of `@classmethod`.
1213*8c35d5eeSXin Li
1214*8c35d5eeSXin Li<a id="s2.17.1-definition"></a>
1215*8c35d5eeSXin Li<a id="2171-definition"></a>
1216*8c35d5eeSXin Li
1217*8c35d5eeSXin Li<a id="decorators-definition"></a>
1218*8c35d5eeSXin Li#### 2.17.1 Definition
1219*8c35d5eeSXin Li
1220*8c35d5eeSXin Li[Decorators for Functions and
1221*8c35d5eeSXin LiMethods](https://docs.python.org/3/glossary.html#term-decorator)
1222*8c35d5eeSXin Li(a.k.a "the `@` notation"). One common decorator is `@property`, used for
1223*8c35d5eeSXin Liconverting ordinary methods into dynamically computed attributes. However, the
1224*8c35d5eeSXin Lidecorator syntax allows for user-defined decorators as well. Specifically, for
1225*8c35d5eeSXin Lisome function `my_decorator`, this:
1226*8c35d5eeSXin Li
1227*8c35d5eeSXin Li```python
1228*8c35d5eeSXin Liclass C(object):
1229*8c35d5eeSXin Li    @my_decorator
1230*8c35d5eeSXin Li    def method(self):
1231*8c35d5eeSXin Li        # method body ...
1232*8c35d5eeSXin Li```
1233*8c35d5eeSXin Li
1234*8c35d5eeSXin Liis equivalent to:
1235*8c35d5eeSXin Li
1236*8c35d5eeSXin Li
1237*8c35d5eeSXin Li```python
1238*8c35d5eeSXin Liclass C(object):
1239*8c35d5eeSXin Li    def method(self):
1240*8c35d5eeSXin Li        # method body ...
1241*8c35d5eeSXin Li    method = my_decorator(method)
1242*8c35d5eeSXin Li```
1243*8c35d5eeSXin Li
1244*8c35d5eeSXin Li<a id="s2.17.2-pros"></a>
1245*8c35d5eeSXin Li<a id="2172-pros"></a>
1246*8c35d5eeSXin Li
1247*8c35d5eeSXin Li<a id="decorators-pros"></a>
1248*8c35d5eeSXin Li#### 2.17.2 Pros
1249*8c35d5eeSXin Li
1250*8c35d5eeSXin LiElegantly specifies some transformation on a method; the transformation might
1251*8c35d5eeSXin Lieliminate some repetitive code, enforce invariants, etc.
1252*8c35d5eeSXin Li
1253*8c35d5eeSXin Li<a id="s2.17.3-cons"></a>
1254*8c35d5eeSXin Li<a id="2173-cons"></a>
1255*8c35d5eeSXin Li
1256*8c35d5eeSXin Li<a id="decorators-cons"></a>
1257*8c35d5eeSXin Li#### 2.17.3 Cons
1258*8c35d5eeSXin Li
1259*8c35d5eeSXin LiDecorators can perform arbitrary operations on a function's arguments or return
1260*8c35d5eeSXin Livalues, resulting in surprising implicit behavior. Additionally, decorators
1261*8c35d5eeSXin Liexecute at import time. Failures in decorator code are pretty much impossible to
1262*8c35d5eeSXin Lirecover from.
1263*8c35d5eeSXin Li
1264*8c35d5eeSXin Li<a id="s2.17.4-decision"></a>
1265*8c35d5eeSXin Li<a id="2174-decision"></a>
1266*8c35d5eeSXin Li
1267*8c35d5eeSXin Li<a id="decorators-decision"></a>
1268*8c35d5eeSXin Li#### 2.17.4 Decision
1269*8c35d5eeSXin Li
1270*8c35d5eeSXin LiUse decorators judiciously when there is a clear advantage. Decorators should
1271*8c35d5eeSXin Lifollow the same import and naming guidelines as functions. Decorator pydoc
1272*8c35d5eeSXin Lishould clearly state that the function is a decorator. Write unit tests for
1273*8c35d5eeSXin Lidecorators.
1274*8c35d5eeSXin Li
1275*8c35d5eeSXin LiAvoid external dependencies in the decorator itself (e.g. don't rely on files,
1276*8c35d5eeSXin Lisockets, database connections, etc.), since they might not be available when the
1277*8c35d5eeSXin Lidecorator runs (at import time, perhaps from `pydoc` or other tools). A
1278*8c35d5eeSXin Lidecorator that is called with valid parameters should (as much as possible) be
1279*8c35d5eeSXin Liguaranteed to succeed in all cases.
1280*8c35d5eeSXin Li
1281*8c35d5eeSXin LiDecorators are a special case of "top level code" - see [main](#s3.17-main) for
1282*8c35d5eeSXin Limore discussion.
1283*8c35d5eeSXin Li
1284*8c35d5eeSXin LiNever use `@staticmethod` unless forced to in order to integrate with an API
1285*8c35d5eeSXin Lidefined in an existing library. Write a module level function instead.
1286*8c35d5eeSXin Li
1287*8c35d5eeSXin LiUse `@classmethod` only when writing a named constructor or a class-specific
1288*8c35d5eeSXin Liroutine that modifies necessary global state such as a process-wide cache.
1289*8c35d5eeSXin Li
1290*8c35d5eeSXin Li<a id="s2.18-threading"></a>
1291*8c35d5eeSXin Li<a id="218-threading"></a>
1292*8c35d5eeSXin Li
1293*8c35d5eeSXin Li<a id="threading"></a>
1294*8c35d5eeSXin Li### 2.18 Threading
1295*8c35d5eeSXin Li
1296*8c35d5eeSXin LiDo not rely on the atomicity of built-in types.
1297*8c35d5eeSXin Li
1298*8c35d5eeSXin LiWhile Python's built-in data types such as dictionaries appear to have atomic
1299*8c35d5eeSXin Lioperations, there are corner cases where they aren't atomic (e.g. if `__hash__`
1300*8c35d5eeSXin Lior `__eq__` are implemented as Python methods) and their atomicity should not be
1301*8c35d5eeSXin Lirelied upon. Neither should you rely on atomic variable assignment (since this
1302*8c35d5eeSXin Liin turn depends on dictionaries).
1303*8c35d5eeSXin Li
1304*8c35d5eeSXin LiUse the Queue module's `Queue` data type as the preferred way to communicate
1305*8c35d5eeSXin Lidata between threads. Otherwise, use the threading module and its locking
1306*8c35d5eeSXin Liprimitives. Learn about the proper use of condition variables so you can use
1307*8c35d5eeSXin Li`threading.Condition` instead of using lower-level locks.
1308*8c35d5eeSXin Li
1309*8c35d5eeSXin Li<a id="s2.19-power-features"></a>
1310*8c35d5eeSXin Li<a id="219-power-features"></a>
1311*8c35d5eeSXin Li
1312*8c35d5eeSXin Li<a id="power-features"></a>
1313*8c35d5eeSXin Li### 2.19 Power Features
1314*8c35d5eeSXin Li
1315*8c35d5eeSXin LiAvoid these features.
1316*8c35d5eeSXin Li
1317*8c35d5eeSXin Li<a id="s2.19.1-definition"></a>
1318*8c35d5eeSXin Li<a id="2191-definition"></a>
1319*8c35d5eeSXin Li
1320*8c35d5eeSXin Li<a id="power-features-definition"></a>
1321*8c35d5eeSXin Li#### 2.19.1 Definition
1322*8c35d5eeSXin Li
1323*8c35d5eeSXin LiPython is an extremely flexible language and gives you many fancy features such
1324*8c35d5eeSXin Lias custom metaclasses, access to bytecode, on-the-fly compilation, dynamic
1325*8c35d5eeSXin Liinheritance, object reparenting, import hacks, reflection (e.g. some uses of
1326*8c35d5eeSXin Li`getattr()`), modification of system internals, etc.
1327*8c35d5eeSXin Li
1328*8c35d5eeSXin Li<a id="s2.19.2-pros"></a>
1329*8c35d5eeSXin Li<a id="2192-pros"></a>
1330*8c35d5eeSXin Li
1331*8c35d5eeSXin Li<a id="power-features-pros"></a>
1332*8c35d5eeSXin Li#### 2.19.2 Pros
1333*8c35d5eeSXin Li
1334*8c35d5eeSXin LiThese are powerful language features. They can make your code more compact.
1335*8c35d5eeSXin Li
1336*8c35d5eeSXin Li<a id="s2.19.3-cons"></a>
1337*8c35d5eeSXin Li<a id="2193-cons"></a>
1338*8c35d5eeSXin Li
1339*8c35d5eeSXin Li<a id="power-features-cons"></a>
1340*8c35d5eeSXin Li#### 2.19.3 Cons
1341*8c35d5eeSXin Li
1342*8c35d5eeSXin LiIt's very tempting to use these "cool" features when they're not absolutely
1343*8c35d5eeSXin Linecessary. It's harder to read, understand, and debug code that's using unusual
1344*8c35d5eeSXin Lifeatures underneath. It doesn't seem that way at first (to the original author),
1345*8c35d5eeSXin Libut when revisiting the code, it tends to be more difficult than code that is
1346*8c35d5eeSXin Lilonger but is straightforward.
1347*8c35d5eeSXin Li
1348*8c35d5eeSXin Li<a id="s2.19.4-decision"></a>
1349*8c35d5eeSXin Li<a id="2194-decision"></a>
1350*8c35d5eeSXin Li
1351*8c35d5eeSXin Li<a id="power-features-decision"></a>
1352*8c35d5eeSXin Li#### 2.19.4 Decision
1353*8c35d5eeSXin Li
1354*8c35d5eeSXin LiAvoid these features in your code.
1355*8c35d5eeSXin Li
1356*8c35d5eeSXin LiStandard library modules and classes that internally use these features are okay
1357*8c35d5eeSXin Lito use (for example, `abc.ABCMeta`, `collections.namedtuple`, `dataclasses`,
1358*8c35d5eeSXin Liand `enum`).
1359*8c35d5eeSXin Li
1360*8c35d5eeSXin Li<a id="s2.20-modern-python"></a>
1361*8c35d5eeSXin Li<a id="220-modern-python"></a>
1362*8c35d5eeSXin Li
1363*8c35d5eeSXin Li<a id="modern-python"></a>
1364*8c35d5eeSXin Li### 2.20 Modern Python: Python 3 and from \_\_future\_\_ imports
1365*8c35d5eeSXin Li
1366*8c35d5eeSXin LiPython 3 is here! While not every project is ready to
1367*8c35d5eeSXin Liuse it yet, all code should be written to be 3 compatible (and tested under
1368*8c35d5eeSXin Li3 when possible).
1369*8c35d5eeSXin Li
1370*8c35d5eeSXin Li<a id="s2.20.1-definition"></a>
1371*8c35d5eeSXin Li<a id="2201-definition"></a>
1372*8c35d5eeSXin Li
1373*8c35d5eeSXin Li<a id="modern-python-definition"></a>
1374*8c35d5eeSXin Li#### 2.20.1 Definition
1375*8c35d5eeSXin Li
1376*8c35d5eeSXin LiPython 3 is a significant change in the Python language. While existing code is
1377*8c35d5eeSXin Lioften written with 2.7 in mind, there are some simple things to do to make code
1378*8c35d5eeSXin Limore explicit about its intentions and thus better prepared for use under Python
1379*8c35d5eeSXin Li3 without modification.
1380*8c35d5eeSXin Li
1381*8c35d5eeSXin Li<a id="s2.20.2-pros"></a>
1382*8c35d5eeSXin Li<a id="2202-pros"></a>
1383*8c35d5eeSXin Li
1384*8c35d5eeSXin Li<a id="modern-python-pros"></a>
1385*8c35d5eeSXin Li#### 2.20.2 Pros
1386*8c35d5eeSXin Li
1387*8c35d5eeSXin LiCode written with Python 3 in mind is more explicit and easier to get running
1388*8c35d5eeSXin Liunder Python 3 once all of the dependencies of your project are ready.
1389*8c35d5eeSXin Li
1390*8c35d5eeSXin Li<a id="s2.20.3-cons"></a>
1391*8c35d5eeSXin Li<a id="2203-cons"></a>
1392*8c35d5eeSXin Li
1393*8c35d5eeSXin Li<a id="modern-python-cons"></a>
1394*8c35d5eeSXin Li#### 2.20.3 Cons
1395*8c35d5eeSXin Li
1396*8c35d5eeSXin LiSome people find the additional boilerplate to be ugly. It's unusual to add
1397*8c35d5eeSXin Liimports to a module that doesn't actually require the features added by the
1398*8c35d5eeSXin Liimport.
1399*8c35d5eeSXin Li
1400*8c35d5eeSXin Li<a id="s2.20.4-decision"></a>
1401*8c35d5eeSXin Li<a id="2204-decision"></a>
1402*8c35d5eeSXin Li
1403*8c35d5eeSXin Li<a id="modern-python-decision"></a>
1404*8c35d5eeSXin Li#### 2.20.4 Decision
1405*8c35d5eeSXin Li
1406*8c35d5eeSXin Li##### from \_\_future\_\_ imports
1407*8c35d5eeSXin Li
1408*8c35d5eeSXin LiUse of `from __future__ import` statements is encouraged. All new code should
1409*8c35d5eeSXin Licontain the following and existing code should be updated to be compatible when
1410*8c35d5eeSXin Lipossible:
1411*8c35d5eeSXin Li
1412*8c35d5eeSXin Li```python
1413*8c35d5eeSXin Lifrom __future__ import absolute_import
1414*8c35d5eeSXin Lifrom __future__ import division
1415*8c35d5eeSXin Lifrom __future__ import print_function
1416*8c35d5eeSXin Li```
1417*8c35d5eeSXin Li
1418*8c35d5eeSXin LiIf you are not already familiar with those, read up on each here: [absolute
1419*8c35d5eeSXin Liimports](https://www.python.org/dev/peps/pep-0328/), [new `/` division
1420*8c35d5eeSXin Libehavior](https://www.python.org/dev/peps/pep-0238/), and [the print
1421*8c35d5eeSXin Lifunction](https://www.python.org/dev/peps/pep-3105/).
1422*8c35d5eeSXin Li
1423*8c35d5eeSXin Li
1424*8c35d5eeSXin LiPlease don't omit or remove these imports, even if they're not currently used in
1425*8c35d5eeSXin Lithe module, unless the code is Python 3 only. It is better to always have the
1426*8c35d5eeSXin Lifuture imports in all files so that they are not forgotten during later edits
1427*8c35d5eeSXin Liwhen someone starts using such a feature.
1428*8c35d5eeSXin Li
1429*8c35d5eeSXin LiThere are other `from __future__` import statements. Use them as you see fit. We
1430*8c35d5eeSXin Lido not include `unicode_literals` in our recommendations as it is not a clear
1431*8c35d5eeSXin Liwin due to implicit default codec conversion consequences it introduces in many
1432*8c35d5eeSXin Liplaces within Python 2.7. Most code is better off with explicit use of `b''` and
1433*8c35d5eeSXin Li`u''` bytes and unicode string literals as necessary.
1434*8c35d5eeSXin Li
1435*8c35d5eeSXin Li##### The six, future, or past libraries
1436*8c35d5eeSXin Li
1437*8c35d5eeSXin LiWhen your project needs to actively support use under both Python 2 and 3, use
1438*8c35d5eeSXin Lithe [six](https://pypi.org/project/six/),
1439*8c35d5eeSXin Li[future](https://pypi.org/project/future/), and
1440*8c35d5eeSXin Li[past](https://pypi.org/project/past/) libraries as you see fit. They exist to
1441*8c35d5eeSXin Limake your code cleaner and life easier.
1442*8c35d5eeSXin Li
1443*8c35d5eeSXin Li<a name="s2.21-typed-code"></a>
1444*8c35d5eeSXin Li<a name="221-type-annotated-code"></a>
1445*8c35d5eeSXin Li<a name="typed-code"></a>
1446*8c35d5eeSXin Li
1447*8c35d5eeSXin Li<a id="typed-code"></a>
1448*8c35d5eeSXin Li### 2.21 Type Annotated Code
1449*8c35d5eeSXin Li
1450*8c35d5eeSXin LiYou can annotate Python 3 code with type hints according to
1451*8c35d5eeSXin Li[PEP-484](https://www.python.org/dev/peps/pep-0484/), and type-check the code at
1452*8c35d5eeSXin Libuild time with a type checking tool like
1453*8c35d5eeSXin Li[pytype](https://github.com/google/pytype).
1454*8c35d5eeSXin Li
1455*8c35d5eeSXin Li
1456*8c35d5eeSXin LiType annotations can be in the source or in a [stub pyi
1457*8c35d5eeSXin Lifile](https://www.python.org/dev/peps/pep-0484/#stub-files). Whenever possible,
1458*8c35d5eeSXin Liannotations should be in the source. Use pyi files for third-party or extension
1459*8c35d5eeSXin Limodules.
1460*8c35d5eeSXin Li
1461*8c35d5eeSXin Li
1462*8c35d5eeSXin Li<a id="s2.21.1-definition"></a>
1463*8c35d5eeSXin Li<a id="2211-definition"></a>
1464*8c35d5eeSXin Li
1465*8c35d5eeSXin Li<a id="typed-code-definition"></a>
1466*8c35d5eeSXin Li#### 2.21.1 Definition
1467*8c35d5eeSXin Li
1468*8c35d5eeSXin LiType annotations (or "type hints") are for function or method arguments and
1469*8c35d5eeSXin Lireturn values:
1470*8c35d5eeSXin Li
1471*8c35d5eeSXin Li```python
1472*8c35d5eeSXin Lidef func(a: int) -> List[int]:
1473*8c35d5eeSXin Li```
1474*8c35d5eeSXin Li
1475*8c35d5eeSXin LiYou can also declare the type of a variable using a special comment:
1476*8c35d5eeSXin Li
1477*8c35d5eeSXin Li```python
1478*8c35d5eeSXin Lia = SomeFunc()  # type: SomeType
1479*8c35d5eeSXin Li```
1480*8c35d5eeSXin Li
1481*8c35d5eeSXin Li<a id="s2.21.2-pros"></a>
1482*8c35d5eeSXin Li<a id="2212-pros"></a>
1483*8c35d5eeSXin Li
1484*8c35d5eeSXin Li<a id="typed-code-pros"></a>
1485*8c35d5eeSXin Li#### 2.21.2 Pros
1486*8c35d5eeSXin Li
1487*8c35d5eeSXin LiType annotations improve the readability and maintainability of your code. The
1488*8c35d5eeSXin Litype checker will convert many runtime errors to build-time errors, and reduce
1489*8c35d5eeSXin Liyour ability to use [Power Features](#power-features).
1490*8c35d5eeSXin Li
1491*8c35d5eeSXin Li<a id="s2.21.3-cons"></a>
1492*8c35d5eeSXin Li<a id="2213-cons"></a>
1493*8c35d5eeSXin Li
1494*8c35d5eeSXin Li<a id="typed-code-cons"></a>
1495*8c35d5eeSXin Li#### 2.21.3 Cons
1496*8c35d5eeSXin Li
1497*8c35d5eeSXin LiYou 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](https://github.com/google/pytype)
1498*8c35d5eeSXin Limay reduce your ability to use [Power Features](#power-features).
1499*8c35d5eeSXin Li
1500*8c35d5eeSXin Li<a id="s2.21.4-decision"></a>
1501*8c35d5eeSXin Li<a id="2214-decision"></a>
1502*8c35d5eeSXin Li
1503*8c35d5eeSXin Li<a id="typed-code-decision"></a>
1504*8c35d5eeSXin Li#### 2.21.4 Decision
1505*8c35d5eeSXin Li
1506*8c35d5eeSXin LiYou are strongly encouraged to enable Python type analysis when updating code.
1507*8c35d5eeSXin LiWhen adding or modifying public APIs, include type annotations and enable
1508*8c35d5eeSXin Lichecking via pytype in the build system. As static analysis is relatively new to
1509*8c35d5eeSXin LiPython, we acknowledge that undesired side-effects (such as
1510*8c35d5eeSXin Liwrongly
1511*8c35d5eeSXin Liinferred types) may prevent adoption by some projects. In those situations,
1512*8c35d5eeSXin Liauthors are encouraged to add a comment with a TODO or link to a bug describing
1513*8c35d5eeSXin Lithe issue(s) currently preventing type annotation adoption in the BUILD file or
1514*8c35d5eeSXin Liin the code itself as appropriate.
1515*8c35d5eeSXin Li
1516*8c35d5eeSXin Li<a id="s3-python-style-rules"></a>
1517*8c35d5eeSXin Li<a id="3-python-style-rules"></a>
1518*8c35d5eeSXin Li
1519*8c35d5eeSXin Li<a id="python-style-rules"></a>
1520*8c35d5eeSXin Li## 3 Python Style Rules
1521*8c35d5eeSXin Li
1522*8c35d5eeSXin Li<a id="s3.1-semicolons"></a>
1523*8c35d5eeSXin Li<a id="31-semicolons"></a>
1524*8c35d5eeSXin Li
1525*8c35d5eeSXin Li<a id="semicolons"></a>
1526*8c35d5eeSXin Li### 3.1 Semicolons
1527*8c35d5eeSXin Li
1528*8c35d5eeSXin LiDo not terminate your lines with semicolons, and do not use semicolons to put
1529*8c35d5eeSXin Litwo statements on the same line.
1530*8c35d5eeSXin Li
1531*8c35d5eeSXin Li<a id="s3.2-line-length"></a>
1532*8c35d5eeSXin Li<a id="32-line-length"></a>
1533*8c35d5eeSXin Li
1534*8c35d5eeSXin Li<a id="line-length"></a>
1535*8c35d5eeSXin Li### 3.2 Line length
1536*8c35d5eeSXin Li
1537*8c35d5eeSXin LiMaximum line length is *80 characters*.
1538*8c35d5eeSXin Li
1539*8c35d5eeSXin LiExplicit exceptions to the 80 character limit:
1540*8c35d5eeSXin Li
1541*8c35d5eeSXin Li-   Long import statements.
1542*8c35d5eeSXin Li-   URLs, pathnames, or long flags in comments.
1543*8c35d5eeSXin Li-   Long string module level constants not containing whitespace that would be
1544*8c35d5eeSXin Li    inconvenient to split across lines such as URLs or pathnames.
1545*8c35d5eeSXin Li-   Pylint disable comments. (e.g.: `# pylint: disable=invalid-name`)
1546*8c35d5eeSXin Li
1547*8c35d5eeSXin LiDo not use backslash line continuation except for `with` statements requiring
1548*8c35d5eeSXin Lithree or more context managers.
1549*8c35d5eeSXin Li
1550*8c35d5eeSXin LiMake use of Python's [implicit line joining inside parentheses, brackets and
1551*8c35d5eeSXin Libraces](http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining).
1552*8c35d5eeSXin LiIf necessary, you can add an extra pair of parentheses around an expression.
1553*8c35d5eeSXin Li
1554*8c35d5eeSXin Li```python
1555*8c35d5eeSXin LiYes: foo_bar(self, width, height, color='black', design=None, x='foo',
1556*8c35d5eeSXin Li             emphasis=None, highlight=0)
1557*8c35d5eeSXin Li
1558*8c35d5eeSXin Li     if (width == 0 and height == 0 and
1559*8c35d5eeSXin Li         color == 'red' and emphasis == 'strong'):
1560*8c35d5eeSXin Li```
1561*8c35d5eeSXin Li
1562*8c35d5eeSXin LiWhen a literal string won't fit on a single line, use parentheses for implicit
1563*8c35d5eeSXin Liline joining.
1564*8c35d5eeSXin Li
1565*8c35d5eeSXin Li```python
1566*8c35d5eeSXin Lix = ('This will build a very long long '
1567*8c35d5eeSXin Li     'long long long long long long string')
1568*8c35d5eeSXin Li```
1569*8c35d5eeSXin Li
1570*8c35d5eeSXin LiWithin comments, put long URLs on their own line if necessary.
1571*8c35d5eeSXin Li
1572*8c35d5eeSXin Li```python
1573*8c35d5eeSXin LiYes:  # See details at
1574*8c35d5eeSXin Li      # http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
1575*8c35d5eeSXin Li```
1576*8c35d5eeSXin Li
1577*8c35d5eeSXin Li```python
1578*8c35d5eeSXin LiNo:  # See details at
1579*8c35d5eeSXin Li     # http://www.example.com/us/developer/documentation/api/content/\
1580*8c35d5eeSXin Li     # v2.0/csv_file_name_extension_full_specification.html
1581*8c35d5eeSXin Li```
1582*8c35d5eeSXin Li
1583*8c35d5eeSXin LiIt is permissible to use backslash continuation when defining a `with` statement
1584*8c35d5eeSXin Liwhose expressions span three or more lines. For two lines of expressions, use a
1585*8c35d5eeSXin Linested `with` statement:
1586*8c35d5eeSXin Li
1587*8c35d5eeSXin Li```python
1588*8c35d5eeSXin LiYes:  with very_long_first_expression_function() as spam, \
1589*8c35d5eeSXin Li           very_long_second_expression_function() as beans, \
1590*8c35d5eeSXin Li           third_thing() as eggs:
1591*8c35d5eeSXin Li          place_order(eggs, beans, spam, beans)
1592*8c35d5eeSXin Li```
1593*8c35d5eeSXin Li
1594*8c35d5eeSXin Li```python
1595*8c35d5eeSXin LiNo:  with VeryLongFirstExpressionFunction() as spam, \
1596*8c35d5eeSXin Li          VeryLongSecondExpressionFunction() as beans:
1597*8c35d5eeSXin Li       PlaceOrder(eggs, beans, spam, beans)
1598*8c35d5eeSXin Li```
1599*8c35d5eeSXin Li
1600*8c35d5eeSXin Li```python
1601*8c35d5eeSXin LiYes:  with very_long_first_expression_function() as spam:
1602*8c35d5eeSXin Li          with very_long_second_expression_function() as beans:
1603*8c35d5eeSXin Li              place_order(beans, spam)
1604*8c35d5eeSXin Li```
1605*8c35d5eeSXin Li
1606*8c35d5eeSXin LiMake note of the indentation of the elements in the line continuation examples
1607*8c35d5eeSXin Liabove; see the [indentation](#s3.4-indentation) section for explanation.
1608*8c35d5eeSXin Li
1609*8c35d5eeSXin LiIn all other cases where a line exceeds 80 characters, and the
1610*8c35d5eeSXin Li[yapf](https://github.com/google/yapf/)
1611*8c35d5eeSXin Liauto-formatter does not help bring the line below the limit, the line is allowed
1612*8c35d5eeSXin Lito exceed this maximum.
1613*8c35d5eeSXin Li
1614*8c35d5eeSXin Li<a id="s3.3-parentheses"></a>
1615*8c35d5eeSXin Li<a id="33-parentheses"></a>
1616*8c35d5eeSXin Li
1617*8c35d5eeSXin Li<a id="parentheses"></a>
1618*8c35d5eeSXin Li### 3.3 Parentheses
1619*8c35d5eeSXin Li
1620*8c35d5eeSXin LiUse parentheses sparingly.
1621*8c35d5eeSXin Li
1622*8c35d5eeSXin LiIt is fine, though not required, to use parentheses around tuples. Do not use
1623*8c35d5eeSXin Lithem in return statements or conditional statements unless using parentheses for
1624*8c35d5eeSXin Liimplied line continuation or to indicate a tuple.
1625*8c35d5eeSXin Li
1626*8c35d5eeSXin Li```python
1627*8c35d5eeSXin LiYes: if foo:
1628*8c35d5eeSXin Li         bar()
1629*8c35d5eeSXin Li     while x:
1630*8c35d5eeSXin Li         x = bar()
1631*8c35d5eeSXin Li     if x and y:
1632*8c35d5eeSXin Li         bar()
1633*8c35d5eeSXin Li     if not x:
1634*8c35d5eeSXin Li         bar()
1635*8c35d5eeSXin Li     # For a 1 item tuple the ()s are more visually obvious than the comma.
1636*8c35d5eeSXin Li     onesie = (foo,)
1637*8c35d5eeSXin Li     return foo
1638*8c35d5eeSXin Li     return spam, beans
1639*8c35d5eeSXin Li     return (spam, beans)
1640*8c35d5eeSXin Li     for (x, y) in dict.items(): ...
1641*8c35d5eeSXin Li```
1642*8c35d5eeSXin Li
1643*8c35d5eeSXin Li```python
1644*8c35d5eeSXin LiNo:  if (x):
1645*8c35d5eeSXin Li         bar()
1646*8c35d5eeSXin Li     if not(x):
1647*8c35d5eeSXin Li         bar()
1648*8c35d5eeSXin Li     return (foo)
1649*8c35d5eeSXin Li```
1650*8c35d5eeSXin Li
1651*8c35d5eeSXin Li<a id="s3.4-indentation"></a>
1652*8c35d5eeSXin Li<a id="34-indentation"></a>
1653*8c35d5eeSXin Li
1654*8c35d5eeSXin Li<a id="indentation"></a>
1655*8c35d5eeSXin Li### 3.4 Indentation
1656*8c35d5eeSXin Li
1657*8c35d5eeSXin LiIndent your code blocks with *4 spaces*.
1658*8c35d5eeSXin Li
1659*8c35d5eeSXin LiNever use tabs or mix tabs and spaces. In cases of implied line continuation,
1660*8c35d5eeSXin Liyou should align wrapped elements either vertically, as per the examples in the
1661*8c35d5eeSXin Li[line length](#s3.2-line-length) section; or using a hanging indent of 4 spaces,
1662*8c35d5eeSXin Liin which case there should be nothing after the open parenthesis or bracket on
1663*8c35d5eeSXin Lithe first line.
1664*8c35d5eeSXin Li
1665*8c35d5eeSXin Li```python
1666*8c35d5eeSXin LiYes:   # Aligned with opening delimiter
1667*8c35d5eeSXin Li       foo = long_function_name(var_one, var_two,
1668*8c35d5eeSXin Li                                var_three, var_four)
1669*8c35d5eeSXin Li       meal = (spam,
1670*8c35d5eeSXin Li               beans)
1671*8c35d5eeSXin Li
1672*8c35d5eeSXin Li       # Aligned with opening delimiter in a dictionary
1673*8c35d5eeSXin Li       foo = {
1674*8c35d5eeSXin Li           long_dictionary_key: value1 +
1675*8c35d5eeSXin Li                                value2,
1676*8c35d5eeSXin Li           ...
1677*8c35d5eeSXin Li       }
1678*8c35d5eeSXin Li
1679*8c35d5eeSXin Li       # 4-space hanging indent; nothing on first line
1680*8c35d5eeSXin Li       foo = long_function_name(
1681*8c35d5eeSXin Li           var_one, var_two, var_three,
1682*8c35d5eeSXin Li           var_four)
1683*8c35d5eeSXin Li       meal = (
1684*8c35d5eeSXin Li           spam,
1685*8c35d5eeSXin Li           beans)
1686*8c35d5eeSXin Li
1687*8c35d5eeSXin Li       # 4-space hanging indent in a dictionary
1688*8c35d5eeSXin Li       foo = {
1689*8c35d5eeSXin Li           long_dictionary_key:
1690*8c35d5eeSXin Li               long_dictionary_value,
1691*8c35d5eeSXin Li           ...
1692*8c35d5eeSXin Li       }
1693*8c35d5eeSXin Li```
1694*8c35d5eeSXin Li
1695*8c35d5eeSXin Li```python
1696*8c35d5eeSXin LiNo:    # Stuff on first line forbidden
1697*8c35d5eeSXin Li       foo = long_function_name(var_one, var_two,
1698*8c35d5eeSXin Li           var_three, var_four)
1699*8c35d5eeSXin Li       meal = (spam,
1700*8c35d5eeSXin Li           beans)
1701*8c35d5eeSXin Li
1702*8c35d5eeSXin Li       # 2-space hanging indent forbidden
1703*8c35d5eeSXin Li       foo = long_function_name(
1704*8c35d5eeSXin Li         var_one, var_two, var_three,
1705*8c35d5eeSXin Li         var_four)
1706*8c35d5eeSXin Li
1707*8c35d5eeSXin Li       # No hanging indent in a dictionary
1708*8c35d5eeSXin Li       foo = {
1709*8c35d5eeSXin Li           long_dictionary_key:
1710*8c35d5eeSXin Li           long_dictionary_value,
1711*8c35d5eeSXin Li           ...
1712*8c35d5eeSXin Li       }
1713*8c35d5eeSXin Li```
1714*8c35d5eeSXin Li
1715*8c35d5eeSXin Li<a id="s3.4.1-trailing_comma"></a>
1716*8c35d5eeSXin Li<a id="341-trailing_comma"></a>
1717*8c35d5eeSXin Li<a id="trailing_comma"></a>
1718*8c35d5eeSXin Li
1719*8c35d5eeSXin Li<a id="trailing-comma"></a>
1720*8c35d5eeSXin Li### 3.4.1 Trailing commas in sequences of items?
1721*8c35d5eeSXin Li
1722*8c35d5eeSXin LiTrailing commas in sequences of items are recommended only when the closing
1723*8c35d5eeSXin Licontainer token `]`, `)`, or `}` does not appear on the same line as the final
1724*8c35d5eeSXin Lielement. The presence of a trailing comma is also used as a hint to our Python
1725*8c35d5eeSXin Licode auto-formatter [YAPF](https://pypi.org/project/yapf/) to direct it to auto-format the container
1726*8c35d5eeSXin Liof items to one item per line when the `,` after the final element is present.
1727*8c35d5eeSXin Li
1728*8c35d5eeSXin Li```python
1729*8c35d5eeSXin LiYes:   golomb3 = [0, 1, 3]
1730*8c35d5eeSXin LiYes:   golomb4 = [
1731*8c35d5eeSXin Li           0,
1732*8c35d5eeSXin Li           1,
1733*8c35d5eeSXin Li           4,
1734*8c35d5eeSXin Li           6,
1735*8c35d5eeSXin Li       ]
1736*8c35d5eeSXin Li```
1737*8c35d5eeSXin Li
1738*8c35d5eeSXin Li```python
1739*8c35d5eeSXin LiNo:    golomb4 = [
1740*8c35d5eeSXin Li           0,
1741*8c35d5eeSXin Li           1,
1742*8c35d5eeSXin Li           4,
1743*8c35d5eeSXin Li           6
1744*8c35d5eeSXin Li       ]
1745*8c35d5eeSXin Li```
1746*8c35d5eeSXin Li
1747*8c35d5eeSXin Li<a id="s3.5-blank-lines"></a>
1748*8c35d5eeSXin Li<a id="35-blank-lines"></a>
1749*8c35d5eeSXin Li
1750*8c35d5eeSXin Li<a id="blank-lines"></a>
1751*8c35d5eeSXin Li### 3.5 Blank Lines
1752*8c35d5eeSXin Li
1753*8c35d5eeSXin LiTwo blank lines between top-level definitions, be they function or class
1754*8c35d5eeSXin Lidefinitions. One blank line between method definitions and between the `class`
1755*8c35d5eeSXin Liline and the first method. No blank line following a `def` line. Use single
1756*8c35d5eeSXin Liblank lines as you judge appropriate within functions or methods.
1757*8c35d5eeSXin Li
1758*8c35d5eeSXin Li<a id="s3.6-whitespace"></a>
1759*8c35d5eeSXin Li<a id="36-whitespace"></a>
1760*8c35d5eeSXin Li
1761*8c35d5eeSXin Li<a id="whitespace"></a>
1762*8c35d5eeSXin Li### 3.6 Whitespace
1763*8c35d5eeSXin Li
1764*8c35d5eeSXin LiFollow standard typographic rules for the use of spaces around punctuation.
1765*8c35d5eeSXin Li
1766*8c35d5eeSXin LiNo whitespace inside parentheses, brackets or braces.
1767*8c35d5eeSXin Li
1768*8c35d5eeSXin Li```python
1769*8c35d5eeSXin LiYes: spam(ham[1], {eggs: 2}, [])
1770*8c35d5eeSXin Li```
1771*8c35d5eeSXin Li
1772*8c35d5eeSXin Li```python
1773*8c35d5eeSXin LiNo:  spam( ham[ 1 ], { eggs: 2 }, [ ] )
1774*8c35d5eeSXin Li```
1775*8c35d5eeSXin Li
1776*8c35d5eeSXin LiNo whitespace before a comma, semicolon, or colon. Do use whitespace after a
1777*8c35d5eeSXin Licomma, semicolon, or colon, except at the end of the line.
1778*8c35d5eeSXin Li
1779*8c35d5eeSXin Li```python
1780*8c35d5eeSXin LiYes: if x == 4:
1781*8c35d5eeSXin Li         print(x, y)
1782*8c35d5eeSXin Li     x, y = y, x
1783*8c35d5eeSXin Li```
1784*8c35d5eeSXin Li
1785*8c35d5eeSXin Li```python
1786*8c35d5eeSXin LiNo:  if x == 4 :
1787*8c35d5eeSXin Li         print(x , y)
1788*8c35d5eeSXin Li     x , y = y , x
1789*8c35d5eeSXin Li```
1790*8c35d5eeSXin Li
1791*8c35d5eeSXin LiNo whitespace before the open paren/bracket that starts an argument list,
1792*8c35d5eeSXin Liindexing or slicing.
1793*8c35d5eeSXin Li
1794*8c35d5eeSXin Li```python
1795*8c35d5eeSXin LiYes: spam(1)
1796*8c35d5eeSXin Li```
1797*8c35d5eeSXin Li
1798*8c35d5eeSXin Li```python
1799*8c35d5eeSXin LiNo:  spam (1)
1800*8c35d5eeSXin Li```
1801*8c35d5eeSXin Li
1802*8c35d5eeSXin Li
1803*8c35d5eeSXin Li```python
1804*8c35d5eeSXin LiYes: dict['key'] = list[index]
1805*8c35d5eeSXin Li```
1806*8c35d5eeSXin Li
1807*8c35d5eeSXin Li```python
1808*8c35d5eeSXin LiNo:  dict ['key'] = list [index]
1809*8c35d5eeSXin Li```
1810*8c35d5eeSXin Li
1811*8c35d5eeSXin LiNo trailing whitespace.
1812*8c35d5eeSXin Li
1813*8c35d5eeSXin LiSurround binary operators with a single space on either side for assignment
1814*8c35d5eeSXin Li(`=`), comparisons (`==, <, >, !=, <>, <=, >=, in, not in, is, is not`), and
1815*8c35d5eeSXin LiBooleans (`and, or, not`). Use your better judgment for the insertion of spaces
1816*8c35d5eeSXin Liaround arithmetic operators (`+`, `-`, `*`, `/`, `//`, `%`, `**`, `@`).
1817*8c35d5eeSXin Li
1818*8c35d5eeSXin Li```python
1819*8c35d5eeSXin LiYes: x == 1
1820*8c35d5eeSXin Li```
1821*8c35d5eeSXin Li
1822*8c35d5eeSXin Li```python
1823*8c35d5eeSXin LiNo:  x<1
1824*8c35d5eeSXin Li```
1825*8c35d5eeSXin Li
1826*8c35d5eeSXin LiNever use spaces around `=` when passing keyword arguments or defining a default
1827*8c35d5eeSXin Liparameter value, with one exception: [when a type annotation is
1828*8c35d5eeSXin Lipresent](#typing-default-values), _do_ use spaces around the `=` for the default
1829*8c35d5eeSXin Liparameter value.
1830*8c35d5eeSXin Li
1831*8c35d5eeSXin Li```python
1832*8c35d5eeSXin LiYes: def complex(real, imag=0.0): return Magic(r=real, i=imag)
1833*8c35d5eeSXin LiYes: def complex(real, imag: float = 0.0): return Magic(r=real, i=imag)
1834*8c35d5eeSXin Li```
1835*8c35d5eeSXin Li
1836*8c35d5eeSXin Li```python
1837*8c35d5eeSXin LiNo:  def complex(real, imag = 0.0): return Magic(r = real, i = imag)
1838*8c35d5eeSXin LiNo:  def complex(real, imag: float=0.0): return Magic(r = real, i = imag)
1839*8c35d5eeSXin Li```
1840*8c35d5eeSXin Li
1841*8c35d5eeSXin LiDon't use spaces to vertically align tokens on consecutive lines, since it
1842*8c35d5eeSXin Libecomes a maintenance burden (applies to `:`, `#`, `=`, etc.):
1843*8c35d5eeSXin Li
1844*8c35d5eeSXin Li```python
1845*8c35d5eeSXin LiYes:
1846*8c35d5eeSXin Li  foo = 1000  # comment
1847*8c35d5eeSXin Li  long_name = 2  # comment that should not be aligned
1848*8c35d5eeSXin Li
1849*8c35d5eeSXin Li  dictionary = {
1850*8c35d5eeSXin Li      'foo': 1,
1851*8c35d5eeSXin Li      'long_name': 2,
1852*8c35d5eeSXin Li  }
1853*8c35d5eeSXin Li```
1854*8c35d5eeSXin Li
1855*8c35d5eeSXin Li```python
1856*8c35d5eeSXin LiNo:
1857*8c35d5eeSXin Li  foo       = 1000  # comment
1858*8c35d5eeSXin Li  long_name = 2     # comment that should not be aligned
1859*8c35d5eeSXin Li
1860*8c35d5eeSXin Li  dictionary = {
1861*8c35d5eeSXin Li      'foo'      : 1,
1862*8c35d5eeSXin Li      'long_name': 2,
1863*8c35d5eeSXin Li  }
1864*8c35d5eeSXin Li```
1865*8c35d5eeSXin Li
1866*8c35d5eeSXin Li
1867*8c35d5eeSXin Li<a id="Python_Interpreter"></a>
1868*8c35d5eeSXin Li<a id="s3.7-shebang-line"></a>
1869*8c35d5eeSXin Li<a id="37-shebang-line"></a>
1870*8c35d5eeSXin Li
1871*8c35d5eeSXin Li<a id="shebang-line"></a>
1872*8c35d5eeSXin Li### 3.7 Shebang Line
1873*8c35d5eeSXin Li
1874*8c35d5eeSXin LiMost `.py` files do not need to start with a `#!` line. Start the main file of a
1875*8c35d5eeSXin Liprogram with
1876*8c35d5eeSXin Li`#!/usr/bin/python` with an optional single digit `2` or `3` suffix per
1877*8c35d5eeSXin Li[PEP-394](https://www.google.com/url?sa=D&q=http://www.python.org/dev/peps/pep-0394/).
1878*8c35d5eeSXin Li
1879*8c35d5eeSXin LiThis line is used by the kernel to find the Python interpreter, but is ignored
1880*8c35d5eeSXin Liby Python when importing modules. It is only necessary on a file that will be
1881*8c35d5eeSXin Liexecuted directly.
1882*8c35d5eeSXin Li
1883*8c35d5eeSXin Li<a id="s3.8-comments"></a>
1884*8c35d5eeSXin Li<a id="38-comments-and-docstrings"></a>
1885*8c35d5eeSXin Li
1886*8c35d5eeSXin Li<a id="documentation"></a>
1887*8c35d5eeSXin Li### 3.8 Comments and Docstrings
1888*8c35d5eeSXin Li
1889*8c35d5eeSXin LiBe sure to use the right style for module, function, method docstrings and
1890*8c35d5eeSXin Liinline comments.
1891*8c35d5eeSXin Li
1892*8c35d5eeSXin Li<a id="s3.8.1-comments-in-doc-strings"></a>
1893*8c35d5eeSXin Li<a id="381-docstrings"></a>
1894*8c35d5eeSXin Li<a id="comments-in-doc-strings"></a>
1895*8c35d5eeSXin Li
1896*8c35d5eeSXin Li<a id="docstrings"></a>
1897*8c35d5eeSXin Li#### 3.8.1 Docstrings
1898*8c35d5eeSXin Li
1899*8c35d5eeSXin LiPython uses _docstrings_ to document code. A docstring is a string that is the
1900*8c35d5eeSXin Lifirst statement in a package, module, class or function. These strings can be
1901*8c35d5eeSXin Liextracted automatically through the `__doc__` member of the object and are used
1902*8c35d5eeSXin Liby `pydoc`.
1903*8c35d5eeSXin Li(Try running `pydoc` on your module to see how it looks.) Always use the three
1904*8c35d5eeSXin Lidouble-quote `"""` format for docstrings (per [PEP
1905*8c35d5eeSXin Li257](https://www.google.com/url?sa=D&q=http://www.python.org/dev/peps/pep-0257/)).
1906*8c35d5eeSXin LiA docstring should be organized as a summary line (one physical line) terminated
1907*8c35d5eeSXin Liby a period, question mark, or exclamation point, followed by a blank line,
1908*8c35d5eeSXin Lifollowed by the rest of the docstring starting at the same cursor position as
1909*8c35d5eeSXin Lithe first quote of the first line. There are more formatting guidelines for
1910*8c35d5eeSXin Lidocstrings below.
1911*8c35d5eeSXin Li
1912*8c35d5eeSXin Li<a id="s3.8.2-comments-in-modules"></a>
1913*8c35d5eeSXin Li<a id="382-modules"></a>
1914*8c35d5eeSXin Li<a id="comments-in-modules"></a>
1915*8c35d5eeSXin Li
1916*8c35d5eeSXin Li<a id="module-docs"></a>
1917*8c35d5eeSXin Li#### 3.8.2 Modules
1918*8c35d5eeSXin Li
1919*8c35d5eeSXin LiEvery file should contain license boilerplate.
1920*8c35d5eeSXin LiChoose the appropriate boilerplate for the license used by the project (for
1921*8c35d5eeSXin Liexample, Apache 2.0, BSD, LGPL, GPL)
1922*8c35d5eeSXin Li
1923*8c35d5eeSXin LiFiles should start with a docstring describing the contents and usage of the
1924*8c35d5eeSXin Limodule.
1925*8c35d5eeSXin Li```python
1926*8c35d5eeSXin Li"""A one line summary of the module or program, terminated by a period.
1927*8c35d5eeSXin Li
1928*8c35d5eeSXin LiLeave one blank line.  The rest of this docstring should contain an
1929*8c35d5eeSXin Lioverall description of the module or program.  Optionally, it may also
1930*8c35d5eeSXin Licontain a brief description of exported classes and functions and/or usage
1931*8c35d5eeSXin Liexamples.
1932*8c35d5eeSXin Li
1933*8c35d5eeSXin Li  Typical usage example:
1934*8c35d5eeSXin Li
1935*8c35d5eeSXin Li  foo = ClassFoo()
1936*8c35d5eeSXin Li  bar = foo.FunctionBar()
1937*8c35d5eeSXin Li"""
1938*8c35d5eeSXin Li```
1939*8c35d5eeSXin Li
1940*8c35d5eeSXin Li
1941*8c35d5eeSXin Li<a id="s3.8.3-functions-and-methods"></a>
1942*8c35d5eeSXin Li<a id="383-functions-and-methods"></a>
1943*8c35d5eeSXin Li<a id="functions-and-methods"></a>
1944*8c35d5eeSXin Li
1945*8c35d5eeSXin Li<a id="function-docs"></a>
1946*8c35d5eeSXin Li#### 3.8.3 Functions and Methods
1947*8c35d5eeSXin Li
1948*8c35d5eeSXin LiIn this section, "function" means a method, function, or generator.
1949*8c35d5eeSXin Li
1950*8c35d5eeSXin LiA function must have a docstring, unless it meets all of the following criteria:
1951*8c35d5eeSXin Li
1952*8c35d5eeSXin Li-   not externally visible
1953*8c35d5eeSXin Li-   very short
1954*8c35d5eeSXin Li-   obvious
1955*8c35d5eeSXin Li
1956*8c35d5eeSXin LiA docstring should give enough information to write a call to the function
1957*8c35d5eeSXin Liwithout reading the function's code. The docstring should be descriptive-style
1958*8c35d5eeSXin Li(`"""Fetches rows from a Bigtable."""`) rather than imperative-style (`"""Fetch
1959*8c35d5eeSXin Lirows from a Bigtable."""`), except for `@property` data descriptors, which
1960*8c35d5eeSXin Lishould use the <a href="#384-classes">same style as attributes</a>. A docstring
1961*8c35d5eeSXin Lishould describe the function's calling syntax and its semantics, not its
1962*8c35d5eeSXin Liimplementation. For tricky code, comments alongside the code are more
1963*8c35d5eeSXin Liappropriate than using docstrings.
1964*8c35d5eeSXin Li
1965*8c35d5eeSXin LiA method that overrides a method from a base class may have a simple docstring
1966*8c35d5eeSXin Lisending the reader to its overridden method's docstring, such as `"""See base
1967*8c35d5eeSXin Liclass."""`. The rationale is that there is no need to repeat in many places
1968*8c35d5eeSXin Lidocumentation that is already present in the base method's docstring. However,
1969*8c35d5eeSXin Liif the overriding method's behavior is substantially different from the
1970*8c35d5eeSXin Lioverridden method, or details need to be provided (e.g., documenting additional
1971*8c35d5eeSXin Liside effects), a docstring with at least those differences is required on the
1972*8c35d5eeSXin Lioverriding method.
1973*8c35d5eeSXin Li
1974*8c35d5eeSXin LiCertain aspects of a function should be documented in special sections, listed
1975*8c35d5eeSXin Libelow. Each section begins with a heading line, which ends with a colon. All
1976*8c35d5eeSXin Lisections other than the heading should maintain a hanging indent of two or four
1977*8c35d5eeSXin Lispaces (be consistent within a file). These sections can be omitted in cases
1978*8c35d5eeSXin Liwhere the function's name and signature are informative enough that it can be
1979*8c35d5eeSXin Liaptly described using a one-line docstring.
1980*8c35d5eeSXin Li
1981*8c35d5eeSXin Li<a id="doc-function-args"></a>
1982*8c35d5eeSXin Li[*Args:*](#doc-function-args)
1983*8c35d5eeSXin Li:   List each parameter by name. A description should follow the name, and be
1984*8c35d5eeSXin Li    separated by a colon and a space. If the description is too long to fit on a
1985*8c35d5eeSXin Li    single 80-character line, use a hanging indent of 2 or 4 spaces (be
1986*8c35d5eeSXin Li    consistent with the rest of the file).
1987*8c35d5eeSXin Li
1988*8c35d5eeSXin Li    The description should include required type(s) if the code does not contain
1989*8c35d5eeSXin Li    a corresponding type annotation. If a function accepts `*foo` (variable
1990*8c35d5eeSXin Li    length argument lists) and/or `**bar` (arbitrary keyword arguments), they
1991*8c35d5eeSXin Li    should be listed as `*foo` and `**bar`.
1992*8c35d5eeSXin Li
1993*8c35d5eeSXin Li<a id="doc-function-returns"></a>
1994*8c35d5eeSXin Li[*Returns:* (or *Yields:* for generators)](#doc-function-returns)
1995*8c35d5eeSXin Li:   Describe the type and semantics of the return value. If the function only
1996*8c35d5eeSXin Li    returns None, this section is not required. It may also be omitted if the
1997*8c35d5eeSXin Li    docstring starts with Returns or Yields (e.g. `"""Returns row from Bigtable
1998*8c35d5eeSXin Li    as a tuple of strings."""`) and the opening sentence is sufficient to
1999*8c35d5eeSXin Li    describe return value.
2000*8c35d5eeSXin Li
2001*8c35d5eeSXin Li<a id="doc-function-raises"></a>
2002*8c35d5eeSXin Li[*Raises:*](#doc-function-raises)
2003*8c35d5eeSXin Li:   List all exceptions that are relevant to the interface. You should not
2004*8c35d5eeSXin Li    document exceptions that get raised if the API specified in the docstring is
2005*8c35d5eeSXin Li    violated (because this would paradoxically make behavior under violation of
2006*8c35d5eeSXin Li    the API part of the API).
2007*8c35d5eeSXin Li
2008*8c35d5eeSXin Li```python
2009*8c35d5eeSXin Lidef fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
2010*8c35d5eeSXin Li    """Fetches rows from a Bigtable.
2011*8c35d5eeSXin Li
2012*8c35d5eeSXin Li    Retrieves rows pertaining to the given keys from the Table instance
2013*8c35d5eeSXin Li    represented by big_table.  Silly things may happen if
2014*8c35d5eeSXin Li    other_silly_variable is not None.
2015*8c35d5eeSXin Li
2016*8c35d5eeSXin Li    Args:
2017*8c35d5eeSXin Li        big_table: An open Bigtable Table instance.
2018*8c35d5eeSXin Li        keys: A sequence of strings representing the key of each table row
2019*8c35d5eeSXin Li            to fetch.
2020*8c35d5eeSXin Li        other_silly_variable: Another optional variable, that has a much
2021*8c35d5eeSXin Li            longer name than the other args, and which does nothing.
2022*8c35d5eeSXin Li
2023*8c35d5eeSXin Li    Returns:
2024*8c35d5eeSXin Li        A dict mapping keys to the corresponding table row data
2025*8c35d5eeSXin Li        fetched. Each row is represented as a tuple of strings. For
2026*8c35d5eeSXin Li        example:
2027*8c35d5eeSXin Li
2028*8c35d5eeSXin Li        {'Serak': ('Rigel VII', 'Preparer'),
2029*8c35d5eeSXin Li         'Zim': ('Irk', 'Invader'),
2030*8c35d5eeSXin Li         'Lrrr': ('Omicron Persei 8', 'Emperor')}
2031*8c35d5eeSXin Li
2032*8c35d5eeSXin Li        If a key from the keys argument is missing from the dictionary,
2033*8c35d5eeSXin Li        then that row was not found in the table.
2034*8c35d5eeSXin Li
2035*8c35d5eeSXin Li    Raises:
2036*8c35d5eeSXin Li        IOError: An error occurred accessing the bigtable.Table object.
2037*8c35d5eeSXin Li    """
2038*8c35d5eeSXin Li```
2039*8c35d5eeSXin Li
2040*8c35d5eeSXin Li<a id="s3.8.4-comments-in-classes"></a>
2041*8c35d5eeSXin Li<a id="384-classes"></a>
2042*8c35d5eeSXin Li<a id="comments-in-classes"></a>
2043*8c35d5eeSXin Li
2044*8c35d5eeSXin Li<a id="class-docs"></a>
2045*8c35d5eeSXin Li#### 3.8.4 Classes
2046*8c35d5eeSXin Li
2047*8c35d5eeSXin LiClasses should have a docstring below the class definition describing the class.
2048*8c35d5eeSXin LiIf your class has public attributes, they should be documented here in an
2049*8c35d5eeSXin Li`Attributes` section and follow the same formatting as a
2050*8c35d5eeSXin Li[function's `Args`](#doc-function-args) section.
2051*8c35d5eeSXin Li
2052*8c35d5eeSXin Li```python
2053*8c35d5eeSXin Liclass SampleClass(object):
2054*8c35d5eeSXin Li    """Summary of class here.
2055*8c35d5eeSXin Li
2056*8c35d5eeSXin Li    Longer class information....
2057*8c35d5eeSXin Li    Longer class information....
2058*8c35d5eeSXin Li
2059*8c35d5eeSXin Li    Attributes:
2060*8c35d5eeSXin Li        likes_spam: A boolean indicating if we like SPAM or not.
2061*8c35d5eeSXin Li        eggs: An integer count of the eggs we have laid.
2062*8c35d5eeSXin Li    """
2063*8c35d5eeSXin Li
2064*8c35d5eeSXin Li    def __init__(self, likes_spam=False):
2065*8c35d5eeSXin Li        """Inits SampleClass with blah."""
2066*8c35d5eeSXin Li        self.likes_spam = likes_spam
2067*8c35d5eeSXin Li        self.eggs = 0
2068*8c35d5eeSXin Li
2069*8c35d5eeSXin Li    def public_method(self):
2070*8c35d5eeSXin Li        """Performs operation blah."""
2071*8c35d5eeSXin Li```
2072*8c35d5eeSXin Li
2073*8c35d5eeSXin Li<a id="comments-in-block-and-inline"></a>
2074*8c35d5eeSXin Li<a id="s3.8.5-comments-in-block-and-inline"></a>
2075*8c35d5eeSXin Li<a id="385-block-and-inline-comments"></a>
2076*8c35d5eeSXin Li
2077*8c35d5eeSXin Li<a id="comments"></a>
2078*8c35d5eeSXin Li#### 3.8.5 Block and Inline Comments
2079*8c35d5eeSXin Li
2080*8c35d5eeSXin LiThe final place to have comments is in tricky parts of the code. If you're going
2081*8c35d5eeSXin Lito have to explain it at the next [code
2082*8c35d5eeSXin Lireview](http://en.wikipedia.org/wiki/Code_review), you should comment it
2083*8c35d5eeSXin Linow. Complicated operations get a few lines of comments before the operations
2084*8c35d5eeSXin Licommence. Non-obvious ones get comments at the end of the line.
2085*8c35d5eeSXin Li
2086*8c35d5eeSXin Li```python
2087*8c35d5eeSXin Li# We use a weighted dictionary search to find out where i is in
2088*8c35d5eeSXin Li# the array.  We extrapolate position based on the largest num
2089*8c35d5eeSXin Li# in the array and the array size and then do binary search to
2090*8c35d5eeSXin Li# get the exact number.
2091*8c35d5eeSXin Li
2092*8c35d5eeSXin Liif i & (i-1) == 0:  # True if i is 0 or a power of 2.
2093*8c35d5eeSXin Li```
2094*8c35d5eeSXin Li
2095*8c35d5eeSXin LiTo improve legibility, these comments should start at least 2 spaces away from
2096*8c35d5eeSXin Lithe code with the comment character `#`, followed by at least one space before
2097*8c35d5eeSXin Lithe text of the comment itself.
2098*8c35d5eeSXin Li
2099*8c35d5eeSXin LiOn the other hand, never describe the code. Assume the person reading the code
2100*8c35d5eeSXin Liknows Python (though not what you're trying to do) better than you do.
2101*8c35d5eeSXin Li
2102*8c35d5eeSXin Li```python
2103*8c35d5eeSXin Li# BAD COMMENT: Now go through the b array and make sure whenever i occurs
2104*8c35d5eeSXin Li# the next element is i+1
2105*8c35d5eeSXin Li```
2106*8c35d5eeSXin Li
2107*8c35d5eeSXin Li<!-- The next section is copied from the C++ style guide. -->
2108*8c35d5eeSXin Li
2109*8c35d5eeSXin Li<a id="s3.8.6-punctuation-spelling-and-grammar"></a>
2110*8c35d5eeSXin Li<a id="386-punctuation-spelling-and-grammar"></a>
2111*8c35d5eeSXin Li<a id="spelling"></a>
2112*8c35d5eeSXin Li<a id="punctuation"></a>
2113*8c35d5eeSXin Li<a id="grammar"></a>
2114*8c35d5eeSXin Li
2115*8c35d5eeSXin Li<a id="punctuation-spelling-grammar"></a>
2116*8c35d5eeSXin Li#### 3.8.6 Punctuation, Spelling and Grammar
2117*8c35d5eeSXin Li
2118*8c35d5eeSXin LiPay attention to punctuation, spelling, and grammar; it is easier to read
2119*8c35d5eeSXin Liwell-written comments than badly written ones.
2120*8c35d5eeSXin Li
2121*8c35d5eeSXin LiComments should be as readable as narrative text, with proper capitalization and
2122*8c35d5eeSXin Lipunctuation. In many cases, complete sentences are more readable than sentence
2123*8c35d5eeSXin Lifragments. Shorter comments, such as comments at the end of a line of code, can
2124*8c35d5eeSXin Lisometimes be less formal, but you should be consistent with your style.
2125*8c35d5eeSXin Li
2126*8c35d5eeSXin LiAlthough it can be frustrating to have a code reviewer point out that you are
2127*8c35d5eeSXin Liusing a comma when you should be using a semicolon, it is very important that
2128*8c35d5eeSXin Lisource code maintain a high level of clarity and readability. Proper
2129*8c35d5eeSXin Lipunctuation, spelling, and grammar help with that goal.
2130*8c35d5eeSXin Li
2131*8c35d5eeSXin Li<a id="s3.9-classes"></a>
2132*8c35d5eeSXin Li<a id="39-classes"></a>
2133*8c35d5eeSXin Li
2134*8c35d5eeSXin Li<a id="classes"></a>
2135*8c35d5eeSXin Li### 3.9 Classes
2136*8c35d5eeSXin Li
2137*8c35d5eeSXin LiIf a class inherits from no other base classes, explicitly inherit from
2138*8c35d5eeSXin Li`object`. This also applies to nested classes.
2139*8c35d5eeSXin Li
2140*8c35d5eeSXin Li```python
2141*8c35d5eeSXin LiYes: class SampleClass(object):
2142*8c35d5eeSXin Li         pass
2143*8c35d5eeSXin Li
2144*8c35d5eeSXin Li
2145*8c35d5eeSXin Li     class OuterClass(object):
2146*8c35d5eeSXin Li
2147*8c35d5eeSXin Li         class InnerClass(object):
2148*8c35d5eeSXin Li             pass
2149*8c35d5eeSXin Li
2150*8c35d5eeSXin Li
2151*8c35d5eeSXin Li     class ChildClass(ParentClass):
2152*8c35d5eeSXin Li         """Explicitly inherits from another class already."""
2153*8c35d5eeSXin Li
2154*8c35d5eeSXin Li```
2155*8c35d5eeSXin Li
2156*8c35d5eeSXin Li```python
2157*8c35d5eeSXin LiNo: class SampleClass:
2158*8c35d5eeSXin Li        pass
2159*8c35d5eeSXin Li
2160*8c35d5eeSXin Li
2161*8c35d5eeSXin Li    class OuterClass:
2162*8c35d5eeSXin Li
2163*8c35d5eeSXin Li        class InnerClass:
2164*8c35d5eeSXin Li            pass
2165*8c35d5eeSXin Li```
2166*8c35d5eeSXin Li
2167*8c35d5eeSXin LiInheriting from `object` is needed to make properties work properly in Python 2
2168*8c35d5eeSXin Liand can protect your code from potential incompatibility with Python 3. It also
2169*8c35d5eeSXin Lidefines special methods that implement the default semantics of objects
2170*8c35d5eeSXin Liincluding `__new__`, `__init__`, `__delattr__`, `__getattribute__`,
2171*8c35d5eeSXin Li`__setattr__`, `__hash__`, `__repr__`, and `__str__`.
2172*8c35d5eeSXin Li
2173*8c35d5eeSXin Li<a id="s3.10-strings"></a>
2174*8c35d5eeSXin Li<a id="310-strings"></a>
2175*8c35d5eeSXin Li
2176*8c35d5eeSXin Li<a id="strings"></a>
2177*8c35d5eeSXin Li### 3.10 Strings
2178*8c35d5eeSXin Li
2179*8c35d5eeSXin LiUse the `format` method or the `%` operator for formatting strings, even when
2180*8c35d5eeSXin Lithe parameters are all strings. Use your best judgment to decide between `+` and
2181*8c35d5eeSXin Li`%` (or `format`) though.
2182*8c35d5eeSXin Li
2183*8c35d5eeSXin Li```python
2184*8c35d5eeSXin LiYes: x = a + b
2185*8c35d5eeSXin Li     x = '%s, %s!' % (imperative, expletive)
2186*8c35d5eeSXin Li     x = '{}, {}'.format(first, second)
2187*8c35d5eeSXin Li     x = 'name: %s; score: %d' % (name, n)
2188*8c35d5eeSXin Li     x = 'name: {}; score: {}'.format(name, n)
2189*8c35d5eeSXin Li     x = f'name: {name}; score: {n}'  # Python 3.6+
2190*8c35d5eeSXin Li```
2191*8c35d5eeSXin Li
2192*8c35d5eeSXin Li```python
2193*8c35d5eeSXin LiNo: x = '%s%s' % (a, b)  # use + in this case
2194*8c35d5eeSXin Li    x = '{}{}'.format(a, b)  # use + in this case
2195*8c35d5eeSXin Li    x = first + ', ' + second
2196*8c35d5eeSXin Li    x = 'name: ' + name + '; score: ' + str(n)
2197*8c35d5eeSXin Li```
2198*8c35d5eeSXin Li
2199*8c35d5eeSXin LiAvoid using the `+` and `+=` operators to accumulate a string within a loop.
2200*8c35d5eeSXin LiSince strings are immutable, this creates unnecessary temporary objects and
2201*8c35d5eeSXin Liresults in quadratic rather than linear running time. Instead, add each
2202*8c35d5eeSXin Lisubstring to a list and `''.join` the list after the loop terminates (or, write
2203*8c35d5eeSXin Lieach substring to a `io.BytesIO` buffer).
2204*8c35d5eeSXin Li
2205*8c35d5eeSXin Li```python
2206*8c35d5eeSXin LiYes: items = ['<table>']
2207*8c35d5eeSXin Li     for last_name, first_name in employee_list:
2208*8c35d5eeSXin Li         items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
2209*8c35d5eeSXin Li     items.append('</table>')
2210*8c35d5eeSXin Li     employee_table = ''.join(items)
2211*8c35d5eeSXin Li```
2212*8c35d5eeSXin Li
2213*8c35d5eeSXin Li```python
2214*8c35d5eeSXin LiNo: employee_table = '<table>'
2215*8c35d5eeSXin Li    for last_name, first_name in employee_list:
2216*8c35d5eeSXin Li        employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
2217*8c35d5eeSXin Li    employee_table += '</table>'
2218*8c35d5eeSXin Li```
2219*8c35d5eeSXin Li
2220*8c35d5eeSXin LiBe consistent with your choice of string quote character within a file. Pick `'`
2221*8c35d5eeSXin Lior `"` and stick with it. It is okay to use the other quote character on a
2222*8c35d5eeSXin Listring to avoid the need to `\\ ` escape within the string.
2223*8c35d5eeSXin Li
2224*8c35d5eeSXin Li```python
2225*8c35d5eeSXin LiYes:
2226*8c35d5eeSXin Li  Python('Why are you hiding your eyes?')
2227*8c35d5eeSXin Li  Gollum("I'm scared of lint errors.")
2228*8c35d5eeSXin Li  Narrator('"Good!" thought a happy Python reviewer.')
2229*8c35d5eeSXin Li```
2230*8c35d5eeSXin Li
2231*8c35d5eeSXin Li```python
2232*8c35d5eeSXin LiNo:
2233*8c35d5eeSXin Li  Python("Why are you hiding your eyes?")
2234*8c35d5eeSXin Li  Gollum('The lint. It burns. It burns us.')
2235*8c35d5eeSXin Li  Gollum("Always the great lint. Watching. Watching.")
2236*8c35d5eeSXin Li```
2237*8c35d5eeSXin Li
2238*8c35d5eeSXin LiPrefer `"""` for multi-line strings rather than `'''`. Projects may choose to
2239*8c35d5eeSXin Liuse `'''` for all non-docstring multi-line strings if and only if they also use
2240*8c35d5eeSXin Li`'` for regular strings. Docstrings must use `"""` regardless.
2241*8c35d5eeSXin Li
2242*8c35d5eeSXin LiMulti-line strings do not flow with the indentation of the rest of the program.
2243*8c35d5eeSXin LiIf you need to avoid embedding extra space in the string, use either
2244*8c35d5eeSXin Liconcatenated single-line strings or a multi-line string with
2245*8c35d5eeSXin Li[`textwrap.dedent()`](https://docs.python.org/3/library/textwrap.html#textwrap.dedent)
2246*8c35d5eeSXin Lito remove the initial space on each line:
2247*8c35d5eeSXin Li
2248*8c35d5eeSXin Li```python
2249*8c35d5eeSXin Li  No:
2250*8c35d5eeSXin Li  long_string = """This is pretty ugly.
2251*8c35d5eeSXin LiDon't do this.
2252*8c35d5eeSXin Li"""
2253*8c35d5eeSXin Li```
2254*8c35d5eeSXin Li
2255*8c35d5eeSXin Li```python
2256*8c35d5eeSXin Li  Yes:
2257*8c35d5eeSXin Li  long_string = """This is fine if your use case can accept
2258*8c35d5eeSXin Li      extraneous leading spaces."""
2259*8c35d5eeSXin Li```
2260*8c35d5eeSXin Li
2261*8c35d5eeSXin Li```python
2262*8c35d5eeSXin Li  Yes:
2263*8c35d5eeSXin Li  long_string = ("And this is fine if you can not accept\n" +
2264*8c35d5eeSXin Li                 "extraneous leading spaces.")
2265*8c35d5eeSXin Li```
2266*8c35d5eeSXin Li
2267*8c35d5eeSXin Li```python
2268*8c35d5eeSXin Li  Yes:
2269*8c35d5eeSXin Li  long_string = ("And this too is fine if you can not accept\n"
2270*8c35d5eeSXin Li                 "extraneous leading spaces.")
2271*8c35d5eeSXin Li```
2272*8c35d5eeSXin Li
2273*8c35d5eeSXin Li```python
2274*8c35d5eeSXin Li  Yes:
2275*8c35d5eeSXin Li  import textwrap
2276*8c35d5eeSXin Li
2277*8c35d5eeSXin Li  long_string = textwrap.dedent("""\
2278*8c35d5eeSXin Li      This is also fine, because textwrap.dedent()
2279*8c35d5eeSXin Li      will collapse common leading spaces in each line.""")
2280*8c35d5eeSXin Li```
2281*8c35d5eeSXin Li
2282*8c35d5eeSXin Li<a id="s3.11-files-and-sockets"></a>
2283*8c35d5eeSXin Li<a id="311-files-and-sockets"></a>
2284*8c35d5eeSXin Li<a id="files-and-sockets"></a>
2285*8c35d5eeSXin Li
2286*8c35d5eeSXin Li<a id="files"></a>
2287*8c35d5eeSXin Li### 3.11 Files and Sockets
2288*8c35d5eeSXin Li
2289*8c35d5eeSXin LiExplicitly close files and sockets when done with them.
2290*8c35d5eeSXin Li
2291*8c35d5eeSXin LiLeaving files, sockets or other file-like objects open unnecessarily has many
2292*8c35d5eeSXin Lidownsides:
2293*8c35d5eeSXin Li
2294*8c35d5eeSXin Li-   They may consume limited system resources, such as file descriptors. Code
2295*8c35d5eeSXin Li    that deals with many such objects may exhaust those resources unnecessarily
2296*8c35d5eeSXin Li    if they're not returned to the system promptly after use.
2297*8c35d5eeSXin Li-   Holding files open may prevent other actions such as moving or deleting
2298*8c35d5eeSXin Li    them.
2299*8c35d5eeSXin Li-   Files and sockets that are shared throughout a program may inadvertently be
2300*8c35d5eeSXin Li    read from or written to after logically being closed. If they are actually
2301*8c35d5eeSXin Li    closed, attempts to read or write from them will throw exceptions, making
2302*8c35d5eeSXin Li    the problem known sooner.
2303*8c35d5eeSXin Li
2304*8c35d5eeSXin LiFurthermore, while files and sockets are automatically closed when the file
2305*8c35d5eeSXin Liobject is destructed, tying the lifetime of the file object to the state of the
2306*8c35d5eeSXin Lifile is poor practice:
2307*8c35d5eeSXin Li
2308*8c35d5eeSXin Li-   There are no guarantees as to when the runtime will actually run the file's
2309*8c35d5eeSXin Li    destructor. Different Python implementations use different memory management
2310*8c35d5eeSXin Li    techniques, such as delayed Garbage Collection, which may increase the
2311*8c35d5eeSXin Li    object's lifetime arbitrarily and indefinitely.
2312*8c35d5eeSXin Li-   Unexpected references to the file, e.g. in globals or exception tracebacks,
2313*8c35d5eeSXin Li    may keep it around longer than intended.
2314*8c35d5eeSXin Li
2315*8c35d5eeSXin LiThe preferred way to manage files is using the ["with"
2316*8c35d5eeSXin Listatement](http://docs.python.org/reference/compound_stmts.html#the-with-statement):
2317*8c35d5eeSXin Li
2318*8c35d5eeSXin Li```python
2319*8c35d5eeSXin Liwith open("hello.txt") as hello_file:
2320*8c35d5eeSXin Li    for line in hello_file:
2321*8c35d5eeSXin Li        print(line)
2322*8c35d5eeSXin Li```
2323*8c35d5eeSXin Li
2324*8c35d5eeSXin LiFor file-like objects that do not support the "with" statement, use
2325*8c35d5eeSXin Li`contextlib.closing()`:
2326*8c35d5eeSXin Li
2327*8c35d5eeSXin Li```python
2328*8c35d5eeSXin Liimport contextlib
2329*8c35d5eeSXin Li
2330*8c35d5eeSXin Liwith contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
2331*8c35d5eeSXin Li    for line in front_page:
2332*8c35d5eeSXin Li        print(line)
2333*8c35d5eeSXin Li```
2334*8c35d5eeSXin Li
2335*8c35d5eeSXin Li<a id="s3.12-todo-comments"></a>
2336*8c35d5eeSXin Li<a id="312-todo-comments"></a>
2337*8c35d5eeSXin Li
2338*8c35d5eeSXin Li<a id="todo"></a>
2339*8c35d5eeSXin Li### 3.12 TODO Comments
2340*8c35d5eeSXin Li
2341*8c35d5eeSXin LiUse `TODO` comments for code that is temporary, a short-term solution, or
2342*8c35d5eeSXin Ligood-enough but not perfect.
2343*8c35d5eeSXin Li
2344*8c35d5eeSXin LiA `TODO` comment begins with the string `TODO` in all caps and a parenthesized
2345*8c35d5eeSXin Liname, e-mail address, or other identifier
2346*8c35d5eeSXin Liof the person or issue with the best context about the problem. This is followed
2347*8c35d5eeSXin Liby an explanation of what there is to do.
2348*8c35d5eeSXin Li
2349*8c35d5eeSXin LiThe purpose is to have a consistent `TODO` format that can be searched to find
2350*8c35d5eeSXin Liout how to get more details. A `TODO` is not a commitment that the person
2351*8c35d5eeSXin Lireferenced will fix the problem. Thus when you create a
2352*8c35d5eeSXin Li`TODO`, it is almost always your name
2353*8c35d5eeSXin Lithat is given.
2354*8c35d5eeSXin Li
2355*8c35d5eeSXin Li```python
2356*8c35d5eeSXin Li# TODO([email protected]): Use a "*" here for string repetition.
2357*8c35d5eeSXin Li# TODO(Zeke) Change this to use relations.
2358*8c35d5eeSXin Li```
2359*8c35d5eeSXin Li
2360*8c35d5eeSXin LiIf your `TODO` is of the form "At a future date do something" make sure that you
2361*8c35d5eeSXin Lieither include a very specific date ("Fix by November 2009") or a very specific
2362*8c35d5eeSXin Lievent ("Remove this code when all clients can handle XML responses.").
2363*8c35d5eeSXin Li
2364*8c35d5eeSXin Li<a id="s3.13-imports-formatting"></a>
2365*8c35d5eeSXin Li<a id="313-imports-formatting"></a>
2366*8c35d5eeSXin Li
2367*8c35d5eeSXin Li<a id="imports-formatting"></a>
2368*8c35d5eeSXin Li### 3.13 Imports formatting
2369*8c35d5eeSXin Li
2370*8c35d5eeSXin LiImports should be on separate lines.
2371*8c35d5eeSXin Li
2372*8c35d5eeSXin LiE.g.:
2373*8c35d5eeSXin Li
2374*8c35d5eeSXin Li```python
2375*8c35d5eeSXin LiYes: import os
2376*8c35d5eeSXin Li     import sys
2377*8c35d5eeSXin Li```
2378*8c35d5eeSXin Li
2379*8c35d5eeSXin Li```python
2380*8c35d5eeSXin LiNo:  import os, sys
2381*8c35d5eeSXin Li```
2382*8c35d5eeSXin Li
2383*8c35d5eeSXin Li
2384*8c35d5eeSXin LiImports are always put at the top of the file, just after any module comments
2385*8c35d5eeSXin Liand docstrings and before module globals and constants. Imports should be
2386*8c35d5eeSXin Ligrouped from most generic to least generic:
2387*8c35d5eeSXin Li
2388*8c35d5eeSXin Li1.  Python future import statements. For example:
2389*8c35d5eeSXin Li
2390*8c35d5eeSXin Li    ```python
2391*8c35d5eeSXin Li    from __future__ import absolute_import
2392*8c35d5eeSXin Li    from __future__ import division
2393*8c35d5eeSXin Li    from __future__ import print_function
2394*8c35d5eeSXin Li    ```
2395*8c35d5eeSXin Li
2396*8c35d5eeSXin Li    See [above](#from-future-imports) for more information about those.
2397*8c35d5eeSXin Li
2398*8c35d5eeSXin Li2.  Python standard library imports. For example:
2399*8c35d5eeSXin Li
2400*8c35d5eeSXin Li    ```python
2401*8c35d5eeSXin Li    import sys
2402*8c35d5eeSXin Li    ```
2403*8c35d5eeSXin Li
2404*8c35d5eeSXin Li3.  [third-party](https://pypi.org/) module
2405*8c35d5eeSXin Li    or package imports. For example:
2406*8c35d5eeSXin Li
2407*8c35d5eeSXin Li
2408*8c35d5eeSXin Li    ```python
2409*8c35d5eeSXin Li    import tensorflow as tf
2410*8c35d5eeSXin Li    ```
2411*8c35d5eeSXin Li
2412*8c35d5eeSXin Li4.  Code repository
2413*8c35d5eeSXin Li    sub-package imports. For example:
2414*8c35d5eeSXin Li
2415*8c35d5eeSXin Li
2416*8c35d5eeSXin Li    ```python
2417*8c35d5eeSXin Li    from otherproject.ai import mind
2418*8c35d5eeSXin Li    ```
2419*8c35d5eeSXin Li
2420*8c35d5eeSXin Li5.  **Deprecated:** application-specific imports that are part of the same
2421*8c35d5eeSXin Li    top level
2422*8c35d5eeSXin Li    sub-package as this file. For example:
2423*8c35d5eeSXin Li
2424*8c35d5eeSXin Li
2425*8c35d5eeSXin Li    ```python
2426*8c35d5eeSXin Li    from myproject.backend.hgwells import time_machine
2427*8c35d5eeSXin Li    ```
2428*8c35d5eeSXin Li
2429*8c35d5eeSXin Li    You may find older Google Python Style code doing this, but it is no longer
2430*8c35d5eeSXin Li    required. **New code is encouraged not to bother with this.** Simply treat
2431*8c35d5eeSXin Li    application-specific sub-package imports the same as other sub-package
2432*8c35d5eeSXin Li    imports.
2433*8c35d5eeSXin Li
2434*8c35d5eeSXin Li
2435*8c35d5eeSXin LiWithin each grouping, imports should be sorted lexicographically, ignoring case,
2436*8c35d5eeSXin Liaccording to each module's full package path. Code may optionally place a blank
2437*8c35d5eeSXin Liline between import sections.
2438*8c35d5eeSXin Li
2439*8c35d5eeSXin Li```python
2440*8c35d5eeSXin Liimport collections
2441*8c35d5eeSXin Liimport queue
2442*8c35d5eeSXin Liimport sys
2443*8c35d5eeSXin Li
2444*8c35d5eeSXin Lifrom absl import app
2445*8c35d5eeSXin Lifrom absl import flags
2446*8c35d5eeSXin Liimport bs4
2447*8c35d5eeSXin Liimport cryptography
2448*8c35d5eeSXin Liimport tensorflow as tf
2449*8c35d5eeSXin Li
2450*8c35d5eeSXin Lifrom book.genres import scifi
2451*8c35d5eeSXin Lifrom myproject.backend.hgwells import time_machine
2452*8c35d5eeSXin Lifrom myproject.backend.state_machine import main_loop
2453*8c35d5eeSXin Lifrom otherproject.ai import body
2454*8c35d5eeSXin Lifrom otherproject.ai import mind
2455*8c35d5eeSXin Lifrom otherproject.ai import soul
2456*8c35d5eeSXin Li
2457*8c35d5eeSXin Li# Older style code may have these imports down here instead:
2458*8c35d5eeSXin Li#from myproject.backend.hgwells import time_machine
2459*8c35d5eeSXin Li#from myproject.backend.state_machine import main_loop
2460*8c35d5eeSXin Li```
2461*8c35d5eeSXin Li
2462*8c35d5eeSXin Li
2463*8c35d5eeSXin Li<a id="s3.14-statements"></a>
2464*8c35d5eeSXin Li<a id="314-statements"></a>
2465*8c35d5eeSXin Li
2466*8c35d5eeSXin Li<a id="statements"></a>
2467*8c35d5eeSXin Li### 3.14 Statements
2468*8c35d5eeSXin Li
2469*8c35d5eeSXin LiGenerally only one statement per line.
2470*8c35d5eeSXin Li
2471*8c35d5eeSXin LiHowever, you may put the result of a test on the same line as the test only if
2472*8c35d5eeSXin Lithe entire statement fits on one line. In particular, you can never do so with
2473*8c35d5eeSXin Li`try`/`except` since the `try` and `except` can't both fit on the same line, and
2474*8c35d5eeSXin Liyou can only do so with an `if` if there is no `else`.
2475*8c35d5eeSXin Li
2476*8c35d5eeSXin Li```python
2477*8c35d5eeSXin LiYes:
2478*8c35d5eeSXin Li
2479*8c35d5eeSXin Li  if foo: bar(foo)
2480*8c35d5eeSXin Li```
2481*8c35d5eeSXin Li
2482*8c35d5eeSXin Li```python
2483*8c35d5eeSXin LiNo:
2484*8c35d5eeSXin Li
2485*8c35d5eeSXin Li  if foo: bar(foo)
2486*8c35d5eeSXin Li  else:   baz(foo)
2487*8c35d5eeSXin Li
2488*8c35d5eeSXin Li  try:               bar(foo)
2489*8c35d5eeSXin Li  except ValueError: baz(foo)
2490*8c35d5eeSXin Li
2491*8c35d5eeSXin Li  try:
2492*8c35d5eeSXin Li      bar(foo)
2493*8c35d5eeSXin Li  except ValueError: baz(foo)
2494*8c35d5eeSXin Li```
2495*8c35d5eeSXin Li
2496*8c35d5eeSXin Li<a id="s3.15-access-control"></a>
2497*8c35d5eeSXin Li<a id="315-access-control"></a>
2498*8c35d5eeSXin Li<a id="access-control"></a>
2499*8c35d5eeSXin Li
2500*8c35d5eeSXin Li<a id="accessors"></a>
2501*8c35d5eeSXin Li### 3.15 Accessors
2502*8c35d5eeSXin Li
2503*8c35d5eeSXin LiIf an accessor function would be trivial, you should use public variables
2504*8c35d5eeSXin Liinstead of accessor functions to avoid the extra cost of function calls in
2505*8c35d5eeSXin LiPython. When more functionality is added you can use `property` to keep the
2506*8c35d5eeSXin Lisyntax consistent.
2507*8c35d5eeSXin Li
2508*8c35d5eeSXin LiOn the other hand, if access is more complex, or the cost of accessing the
2509*8c35d5eeSXin Livariable is significant, you should use function calls (following the
2510*8c35d5eeSXin Li[Naming](#s3.16-naming) guidelines) such as `get_foo()` and
2511*8c35d5eeSXin Li`set_foo()`. If the past behavior allowed access through a property, do not
2512*8c35d5eeSXin Libind the new accessor functions to the property. Any code still attempting to
2513*8c35d5eeSXin Liaccess the variable by the old method should break visibly so they are made
2514*8c35d5eeSXin Liaware of the change in complexity.
2515*8c35d5eeSXin Li
2516*8c35d5eeSXin Li<a id="s3.16-naming"></a>
2517*8c35d5eeSXin Li<a id="316-naming"></a>
2518*8c35d5eeSXin Li
2519*8c35d5eeSXin Li<a id="naming"></a>
2520*8c35d5eeSXin Li### 3.16 Naming
2521*8c35d5eeSXin Li
2522*8c35d5eeSXin Li`module_name`, `package_name`, `ClassName`, `method_name`, `ExceptionName`,
2523*8c35d5eeSXin Li`function_name`, `GLOBAL_CONSTANT_NAME`, `global_var_name`, `instance_var_name`,
2524*8c35d5eeSXin Li`function_parameter_name`, `local_var_name`.
2525*8c35d5eeSXin Li
2526*8c35d5eeSXin Li
2527*8c35d5eeSXin LiFunction names, variable names, and filenames should be descriptive; eschew
2528*8c35d5eeSXin Liabbreviation. In particular, do not use abbreviations that are ambiguous or
2529*8c35d5eeSXin Liunfamiliar to readers outside your project, and do not abbreviate by deleting
2530*8c35d5eeSXin Liletters within a word.
2531*8c35d5eeSXin Li
2532*8c35d5eeSXin LiAlways use a `.py` filename extension. Never use dashes.
2533*8c35d5eeSXin Li
2534*8c35d5eeSXin Li<a id="s3.16.1-names-to-avoid"></a>
2535*8c35d5eeSXin Li<a id="3161-names-to-avoid"></a>
2536*8c35d5eeSXin Li
2537*8c35d5eeSXin Li<a id="names-to-avoid"></a>
2538*8c35d5eeSXin Li#### 3.16.1 Names to Avoid
2539*8c35d5eeSXin Li
2540*8c35d5eeSXin Li-   single character names except for counters or iterators. You may use "e" as
2541*8c35d5eeSXin Li    an exception identifier in try/except statements.
2542*8c35d5eeSXin Li-   dashes (`-`) in any package/module name
2543*8c35d5eeSXin Li-   `__double_leading_and_trailing_underscore__` names (reserved by Python)
2544*8c35d5eeSXin Li
2545*8c35d5eeSXin Li<a id="s3.16.2-naming-conventions"></a>
2546*8c35d5eeSXin Li<a id="3162-naming-convention"></a>
2547*8c35d5eeSXin Li
2548*8c35d5eeSXin Li<a id="naming-conventions"></a>
2549*8c35d5eeSXin Li#### 3.16.2 Naming Conventions
2550*8c35d5eeSXin Li
2551*8c35d5eeSXin Li-   "Internal" means internal to a module, or protected or private within a
2552*8c35d5eeSXin Li    class.
2553*8c35d5eeSXin Li
2554*8c35d5eeSXin Li-   Prepending a single underscore (`_`) has some support for protecting module
2555*8c35d5eeSXin Li    variables and functions (not included with `from module import *`). While
2556*8c35d5eeSXin Li    prepending a double underscore (`__` aka "dunder") to an instance variable
2557*8c35d5eeSXin Li    or method effectively makes the variable or method private to its class
2558*8c35d5eeSXin Li    (using name mangling) we discourage its use as it impacts readability and
2559*8c35d5eeSXin Li    testability and isn't *really* private.
2560*8c35d5eeSXin Li
2561*8c35d5eeSXin Li-   Place related classes and top-level functions together in a
2562*8c35d5eeSXin Li    module.
2563*8c35d5eeSXin Li    Unlike Java, there is no need to limit yourself to one class per module.
2564*8c35d5eeSXin Li
2565*8c35d5eeSXin Li-   Use CapWords for class names, but lower\_with\_under.py for module names.
2566*8c35d5eeSXin Li    Although there are some old modules named CapWords.py, this is now
2567*8c35d5eeSXin Li    discouraged because it's confusing when the module happens to be named after
2568*8c35d5eeSXin Li    a class. ("wait -- did I write `import StringIO` or `from StringIO import
2569*8c35d5eeSXin Li    StringIO`?")
2570*8c35d5eeSXin Li
2571*8c35d5eeSXin Li-   Underscores may appear in *unittest* method names starting with `test` to
2572*8c35d5eeSXin Li    separate logical components of the name, even if those components use
2573*8c35d5eeSXin Li    CapWords. One possible pattern is `test<MethodUnderTest>_<state>`; for
2574*8c35d5eeSXin Li    example `testPop_EmptyStack` is okay. There is no One Correct Way to name
2575*8c35d5eeSXin Li    test methods.
2576*8c35d5eeSXin Li
2577*8c35d5eeSXin Li<a id="s3.16.3-file-naming"></a>
2578*8c35d5eeSXin Li<a id="3163-file-naming"></a>
2579*8c35d5eeSXin Li
2580*8c35d5eeSXin Li<a id="file-naming"></a>
2581*8c35d5eeSXin Li#### 3.16.3 File Naming
2582*8c35d5eeSXin Li
2583*8c35d5eeSXin LiPython filenames must have a `.py` extension and must not contain dashes (`-`).
2584*8c35d5eeSXin LiThis allows them to be imported and unittested. If you want an executable to be
2585*8c35d5eeSXin Liaccessible without the extension, use a symbolic link or a simple bash wrapper
2586*8c35d5eeSXin Licontaining `exec "$0.py" "$@"`.
2587*8c35d5eeSXin Li
2588*8c35d5eeSXin Li<a id="s3.16.4-guidelines-derived-from-guidos-recommendations"></a>
2589*8c35d5eeSXin Li<a id="3164-guidelines-derived-from-guidos-recommendations"></a>
2590*8c35d5eeSXin Li
2591*8c35d5eeSXin Li<a id="guidelines-derived-from-guidos-recommendations"></a>
2592*8c35d5eeSXin Li#### 3.16.4 Guidelines derived from Guido's Recommendations
2593*8c35d5eeSXin Li
2594*8c35d5eeSXin Li<table rules="all" border="1" summary="Guidelines from Guido's Recommendations"
2595*8c35d5eeSXin Li       cellspacing="2" cellpadding="2">
2596*8c35d5eeSXin Li
2597*8c35d5eeSXin Li  <tr>
2598*8c35d5eeSXin Li    <th>Type</th>
2599*8c35d5eeSXin Li    <th>Public</th>
2600*8c35d5eeSXin Li    <th>Internal</th>
2601*8c35d5eeSXin Li  </tr>
2602*8c35d5eeSXin Li
2603*8c35d5eeSXin Li  <tr>
2604*8c35d5eeSXin Li    <td>Packages</td>
2605*8c35d5eeSXin Li    <td><code>lower_with_under</code></td>
2606*8c35d5eeSXin Li    <td></td>
2607*8c35d5eeSXin Li  </tr>
2608*8c35d5eeSXin Li
2609*8c35d5eeSXin Li  <tr>
2610*8c35d5eeSXin Li    <td>Modules</td>
2611*8c35d5eeSXin Li    <td><code>lower_with_under</code></td>
2612*8c35d5eeSXin Li    <td><code>_lower_with_under</code></td>
2613*8c35d5eeSXin Li  </tr>
2614*8c35d5eeSXin Li
2615*8c35d5eeSXin Li  <tr>
2616*8c35d5eeSXin Li    <td>Classes</td>
2617*8c35d5eeSXin Li    <td><code>CapWords</code></td>
2618*8c35d5eeSXin Li    <td><code>_CapWords</code></td>
2619*8c35d5eeSXin Li  </tr>
2620*8c35d5eeSXin Li
2621*8c35d5eeSXin Li  <tr>
2622*8c35d5eeSXin Li    <td>Exceptions</td>
2623*8c35d5eeSXin Li    <td><code>CapWords</code></td>
2624*8c35d5eeSXin Li    <td></td>
2625*8c35d5eeSXin Li  </tr>
2626*8c35d5eeSXin Li
2627*8c35d5eeSXin Li  <tr>
2628*8c35d5eeSXin Li    <td>Functions</td>
2629*8c35d5eeSXin Li    <td><code>lower_with_under()</code></td>
2630*8c35d5eeSXin Li    <td><code>_lower_with_under()</code></td>
2631*8c35d5eeSXin Li  </tr>
2632*8c35d5eeSXin Li
2633*8c35d5eeSXin Li  <tr>
2634*8c35d5eeSXin Li    <td>Global/Class Constants</td>
2635*8c35d5eeSXin Li    <td><code>CAPS_WITH_UNDER</code></td>
2636*8c35d5eeSXin Li    <td><code>_CAPS_WITH_UNDER</code></td>
2637*8c35d5eeSXin Li  </tr>
2638*8c35d5eeSXin Li
2639*8c35d5eeSXin Li  <tr>
2640*8c35d5eeSXin Li    <td>Global/Class Variables</td>
2641*8c35d5eeSXin Li    <td><code>lower_with_under</code></td>
2642*8c35d5eeSXin Li    <td><code>_lower_with_under</code></td>
2643*8c35d5eeSXin Li  </tr>
2644*8c35d5eeSXin Li
2645*8c35d5eeSXin Li  <tr>
2646*8c35d5eeSXin Li    <td>Instance Variables</td>
2647*8c35d5eeSXin Li    <td><code>lower_with_under</code></td>
2648*8c35d5eeSXin Li    <td><code>_lower_with_under</code> (protected)</td>
2649*8c35d5eeSXin Li  </tr>
2650*8c35d5eeSXin Li
2651*8c35d5eeSXin Li  <tr>
2652*8c35d5eeSXin Li    <td>Method Names</td>
2653*8c35d5eeSXin Li    <td><code>lower_with_under()</code></td>
2654*8c35d5eeSXin Li    <td><code>_lower_with_under()</code> (protected)</td>
2655*8c35d5eeSXin Li  </tr>
2656*8c35d5eeSXin Li
2657*8c35d5eeSXin Li  <tr>
2658*8c35d5eeSXin Li    <td>Function/Method Parameters</td>
2659*8c35d5eeSXin Li    <td><code>lower_with_under</code></td>
2660*8c35d5eeSXin Li    <td></td>
2661*8c35d5eeSXin Li  </tr>
2662*8c35d5eeSXin Li
2663*8c35d5eeSXin Li  <tr>
2664*8c35d5eeSXin Li    <td>Local Variables</td>
2665*8c35d5eeSXin Li    <td><code>lower_with_under</code></td>
2666*8c35d5eeSXin Li    <td></td>
2667*8c35d5eeSXin Li  </tr>
2668*8c35d5eeSXin Li
2669*8c35d5eeSXin Li</table>
2670*8c35d5eeSXin Li
2671*8c35d5eeSXin LiWhile Python supports making things private by using a leading double underscore
2672*8c35d5eeSXin Li`__` (aka. "dunder") prefix on a name, this is discouraged. Prefer the use of a
2673*8c35d5eeSXin Lisingle underscore. They are easier to type, read, and to access from small
2674*8c35d5eeSXin Liunittests. Lint warnings take care of invalid access to protected members.
2675*8c35d5eeSXin Li
2676*8c35d5eeSXin Li
2677*8c35d5eeSXin Li<a id="s3.17-main"></a>
2678*8c35d5eeSXin Li<a id="317-main"></a>
2679*8c35d5eeSXin Li
2680*8c35d5eeSXin Li<a id="main"></a>
2681*8c35d5eeSXin Li### 3.17 Main
2682*8c35d5eeSXin Li
2683*8c35d5eeSXin LiEven a file meant to be used as an executable should be importable and a mere
2684*8c35d5eeSXin Liimport should not have the side effect of executing the program's main
2685*8c35d5eeSXin Lifunctionality. The main functionality should be in a `main()` function.
2686*8c35d5eeSXin Li
2687*8c35d5eeSXin LiIn Python, `pydoc` as well as unit tests require modules to be importable. Your
2688*8c35d5eeSXin Licode should always check `if __name__ == '__main__'` before executing your main
2689*8c35d5eeSXin Liprogram so that the main program is not executed when the module is imported.
2690*8c35d5eeSXin Li
2691*8c35d5eeSXin Li```python
2692*8c35d5eeSXin Lidef main():
2693*8c35d5eeSXin Li    ...
2694*8c35d5eeSXin Li
2695*8c35d5eeSXin Liif __name__ == '__main__':
2696*8c35d5eeSXin Li    main()
2697*8c35d5eeSXin Li```
2698*8c35d5eeSXin Li
2699*8c35d5eeSXin LiAll code at the top level will be executed when the module is imported. Be
2700*8c35d5eeSXin Licareful not to call functions, create objects, or perform other operations that
2701*8c35d5eeSXin Lishould not be executed when the file is being `pydoc`ed.
2702*8c35d5eeSXin Li
2703*8c35d5eeSXin Li<a id="s3.18-function-length"></a>
2704*8c35d5eeSXin Li<a id="318-function-length"></a>
2705*8c35d5eeSXin Li
2706*8c35d5eeSXin Li<a id="function-length"></a>
2707*8c35d5eeSXin Li### 3.18 Function length
2708*8c35d5eeSXin Li
2709*8c35d5eeSXin LiPrefer small and focused functions.
2710*8c35d5eeSXin Li
2711*8c35d5eeSXin LiWe recognize that long functions are sometimes appropriate, so no hard limit is
2712*8c35d5eeSXin Liplaced on function length. If a function exceeds about 40 lines, think about
2713*8c35d5eeSXin Liwhether it can be broken up without harming the structure of the program.
2714*8c35d5eeSXin Li
2715*8c35d5eeSXin LiEven if your long function works perfectly now, someone modifying it in a few
2716*8c35d5eeSXin Limonths may add new behavior. This could result in bugs that are hard to find.
2717*8c35d5eeSXin LiKeeping your functions short and simple makes it easier for other people to read
2718*8c35d5eeSXin Liand modify your code.
2719*8c35d5eeSXin Li
2720*8c35d5eeSXin LiYou could find long and complicated functions when working with
2721*8c35d5eeSXin Lisome code. Do not be intimidated by modifying existing code: if working with such
2722*8c35d5eeSXin Lia function proves to be difficult, you find that errors are hard to debug, or
2723*8c35d5eeSXin Liyou want to use a piece of it in several different contexts, consider breaking
2724*8c35d5eeSXin Liup the function into smaller and more manageable pieces.
2725*8c35d5eeSXin Li
2726*8c35d5eeSXin Li<a id="s3.19-type-annotations"></a>
2727*8c35d5eeSXin Li<a id="319-type-annotations"></a>
2728*8c35d5eeSXin Li
2729*8c35d5eeSXin Li<a id="type-annotations"></a>
2730*8c35d5eeSXin Li### 3.19 Type Annotations
2731*8c35d5eeSXin Li
2732*8c35d5eeSXin Li<a id="s3.19.1-general"></a>
2733*8c35d5eeSXin Li<a id="3191-general-rules"></a>
2734*8c35d5eeSXin Li
2735*8c35d5eeSXin Li<a id="typing-general"></a>
2736*8c35d5eeSXin Li#### 3.19.1 General Rules
2737*8c35d5eeSXin Li
2738*8c35d5eeSXin Li* Familiarize yourself with [PEP-484](https://www.python.org/dev/peps/pep-0484/).
2739*8c35d5eeSXin Li* In methods, only annotate `self`, or `cls` if it is necessary for proper type
2740*8c35d5eeSXin Li  information. e.g., `@classmethod def create(cls: Type[T]) -> T: return cls()`
2741*8c35d5eeSXin Li* If any other variable or a returned type should not be expressed, use `Any`.
2742*8c35d5eeSXin Li* You are not required to annotate all the functions in a module.
2743*8c35d5eeSXin Li  -   At least annotate your public APIs.
2744*8c35d5eeSXin Li  -   Use judgment to get to a good balance between safety and clarity on the
2745*8c35d5eeSXin Li      one hand, and flexibility on the other.
2746*8c35d5eeSXin Li  -   Annotate code that is prone to type-related errors (previous bugs or
2747*8c35d5eeSXin Li      complexity).
2748*8c35d5eeSXin Li  -   Annotate code that is hard to understand.
2749*8c35d5eeSXin Li  -   Annotate code as it becomes stable from a types perspective. In many
2750*8c35d5eeSXin Li      cases, you can annotate all the functions in mature code without losing
2751*8c35d5eeSXin Li      too much flexibility.
2752*8c35d5eeSXin Li
2753*8c35d5eeSXin Li
2754*8c35d5eeSXin Li<a id="s3.19.2-line-breaking"></a>
2755*8c35d5eeSXin Li<a id="3192-line-breaking"></a>
2756*8c35d5eeSXin Li
2757*8c35d5eeSXin Li<a id="typing-line-breaking"></a>
2758*8c35d5eeSXin Li#### 3.19.2 Line Breaking
2759*8c35d5eeSXin Li
2760*8c35d5eeSXin LiTry to follow the existing [indentation](#indentation) rules.
2761*8c35d5eeSXin Li
2762*8c35d5eeSXin LiAfter annotating, many function signatures will become "one parameter per line".
2763*8c35d5eeSXin Li
2764*8c35d5eeSXin Li```python
2765*8c35d5eeSXin Lidef my_method(self,
2766*8c35d5eeSXin Li              first_var: int,
2767*8c35d5eeSXin Li              second_var: Foo,
2768*8c35d5eeSXin Li              third_var: Optional[Bar]) -> int:
2769*8c35d5eeSXin Li  ...
2770*8c35d5eeSXin Li```
2771*8c35d5eeSXin Li
2772*8c35d5eeSXin LiAlways prefer breaking between variables, and not for example between variable
2773*8c35d5eeSXin Linames and type annotations. However, if everything fits on the same line,
2774*8c35d5eeSXin Ligo for it.
2775*8c35d5eeSXin Li
2776*8c35d5eeSXin Li```python
2777*8c35d5eeSXin Lidef my_method(self, first_var: int) -> int:
2778*8c35d5eeSXin Li  ...
2779*8c35d5eeSXin Li```
2780*8c35d5eeSXin Li
2781*8c35d5eeSXin LiIf the combination of the function name, the last parameter, and the return type
2782*8c35d5eeSXin Liis too long, indent by 4 in a new line.
2783*8c35d5eeSXin Li
2784*8c35d5eeSXin Li```python
2785*8c35d5eeSXin Lidef my_method(
2786*8c35d5eeSXin Li    self, first_var: int) -> Tuple[MyLongType1, MyLongType1]:
2787*8c35d5eeSXin Li  ...
2788*8c35d5eeSXin Li```
2789*8c35d5eeSXin Li
2790*8c35d5eeSXin LiWhen the return type does not fit on the same line as the last parameter, the
2791*8c35d5eeSXin Lipreferred way is to indent the parameters by 4 on a new line and align the
2792*8c35d5eeSXin Liclosing parenthesis with the def.
2793*8c35d5eeSXin Li
2794*8c35d5eeSXin Li```python
2795*8c35d5eeSXin LiYes:
2796*8c35d5eeSXin Lidef my_method(
2797*8c35d5eeSXin Li    self, other_arg: Optional[MyLongType]
2798*8c35d5eeSXin Li) -> Dict[OtherLongType, MyLongType]:
2799*8c35d5eeSXin Li  ...
2800*8c35d5eeSXin Li```
2801*8c35d5eeSXin Li
2802*8c35d5eeSXin Li`pylint` allows you to move the closing parenthesis to a new line and align
2803*8c35d5eeSXin Liwith the opening one, but this is less readable.
2804*8c35d5eeSXin Li
2805*8c35d5eeSXin Li```python
2806*8c35d5eeSXin LiNo:
2807*8c35d5eeSXin Lidef my_method(self,
2808*8c35d5eeSXin Li              other_arg: Optional[MyLongType]
2809*8c35d5eeSXin Li             ) -> Dict[OtherLongType, MyLongType]:
2810*8c35d5eeSXin Li  ...
2811*8c35d5eeSXin Li```
2812*8c35d5eeSXin Li
2813*8c35d5eeSXin LiAs in the examples above, prefer not to break types. However, sometimes they are
2814*8c35d5eeSXin Litoo long to be on a single line (try to keep sub-types unbroken).
2815*8c35d5eeSXin Li
2816*8c35d5eeSXin Li```python
2817*8c35d5eeSXin Lidef my_method(
2818*8c35d5eeSXin Li    self,
2819*8c35d5eeSXin Li    first_var: Tuple[List[MyLongType1],
2820*8c35d5eeSXin Li                     List[MyLongType2]],
2821*8c35d5eeSXin Li    second_var: List[Dict[
2822*8c35d5eeSXin Li        MyLongType3, MyLongType4]]) -> None:
2823*8c35d5eeSXin Li  ...
2824*8c35d5eeSXin Li```
2825*8c35d5eeSXin Li
2826*8c35d5eeSXin LiIf a single name and type is too long, consider using an
2827*8c35d5eeSXin Li[alias](#typing-aliases) for the type. The last resort is to break after the
2828*8c35d5eeSXin Licolon and indent by 4.
2829*8c35d5eeSXin Li
2830*8c35d5eeSXin Li```python
2831*8c35d5eeSXin LiYes:
2832*8c35d5eeSXin Lidef my_function(
2833*8c35d5eeSXin Li    long_variable_name:
2834*8c35d5eeSXin Li        long_module_name.LongTypeName,
2835*8c35d5eeSXin Li) -> None:
2836*8c35d5eeSXin Li  ...
2837*8c35d5eeSXin Li```
2838*8c35d5eeSXin Li
2839*8c35d5eeSXin Li```python
2840*8c35d5eeSXin LiNo:
2841*8c35d5eeSXin Lidef my_function(
2842*8c35d5eeSXin Li    long_variable_name: long_module_name.
2843*8c35d5eeSXin Li        LongTypeName,
2844*8c35d5eeSXin Li) -> None:
2845*8c35d5eeSXin Li  ...
2846*8c35d5eeSXin Li```
2847*8c35d5eeSXin Li
2848*8c35d5eeSXin Li<a id="s3.19.3-forward-declarations"></a>
2849*8c35d5eeSXin Li<a id="3193-forward-declarations"></a>
2850*8c35d5eeSXin Li
2851*8c35d5eeSXin Li<a id="forward-declarations"></a>
2852*8c35d5eeSXin Li#### 3.19.3 Forward Declarations
2853*8c35d5eeSXin Li
2854*8c35d5eeSXin LiIf you need to use a class name from the same module that is not yet defined --
2855*8c35d5eeSXin Lifor example, if you need the class inside the class declaration, or if you use a
2856*8c35d5eeSXin Liclass that is defined below -- use a string for the class name.
2857*8c35d5eeSXin Li
2858*8c35d5eeSXin Li```python
2859*8c35d5eeSXin Liclass MyClass(object):
2860*8c35d5eeSXin Li
2861*8c35d5eeSXin Li  def __init__(self,
2862*8c35d5eeSXin Li               stack: List["MyClass"]) -> None:
2863*8c35d5eeSXin Li```
2864*8c35d5eeSXin Li
2865*8c35d5eeSXin Li<a id="s3.19.4-default-values"></a>
2866*8c35d5eeSXin Li<a id="3194-default-values"></a>
2867*8c35d5eeSXin Li
2868*8c35d5eeSXin Li<a id="typing-default-values"></a>
2869*8c35d5eeSXin Li#### 3.19.4 Default Values
2870*8c35d5eeSXin Li
2871*8c35d5eeSXin LiAs per
2872*8c35d5eeSXin Li[PEP-008](https://www.python.org/dev/peps/pep-0008/#other-recommendations), use
2873*8c35d5eeSXin Lispaces around the `=` _only_ for arguments that have both a type annotation and
2874*8c35d5eeSXin Lia default value.
2875*8c35d5eeSXin Li
2876*8c35d5eeSXin Li```python
2877*8c35d5eeSXin LiYes:
2878*8c35d5eeSXin Lidef func(a: int = 0) -> int:
2879*8c35d5eeSXin Li  ...
2880*8c35d5eeSXin Li```
2881*8c35d5eeSXin Li```python
2882*8c35d5eeSXin LiNo:
2883*8c35d5eeSXin Lidef func(a:int=0) -> int:
2884*8c35d5eeSXin Li  ...
2885*8c35d5eeSXin Li```
2886*8c35d5eeSXin Li
2887*8c35d5eeSXin Li<a id="s3.19.5-none-type"></a>
2888*8c35d5eeSXin Li<a id="3195-nonetype"></a>
2889*8c35d5eeSXin Li
2890*8c35d5eeSXin Li<a id="none-type"></a>
2891*8c35d5eeSXin Li#### 3.19.5 NoneType
2892*8c35d5eeSXin Li
2893*8c35d5eeSXin LiIn the Python type system, `NoneType` is a "first class" type, and for typing
2894*8c35d5eeSXin Lipurposes, `None` is an alias for `NoneType`. If an argument can be `None`, it
2895*8c35d5eeSXin Lihas to be declared! You can use `Union`, but if there is only one other type,
2896*8c35d5eeSXin Liuse `Optional`.
2897*8c35d5eeSXin Li
2898*8c35d5eeSXin LiUse explicit `Optional` instead of implicit `Optional`. Earlier versions of PEP
2899*8c35d5eeSXin Li484 allowed `a: Text = None` to be interpretted as `a: Optional[Text] = None`,
2900*8c35d5eeSXin Libut that is no longer the preferred behavior.
2901*8c35d5eeSXin Li
2902*8c35d5eeSXin Li```python
2903*8c35d5eeSXin LiYes:
2904*8c35d5eeSXin Lidef func(a: Optional[Text], b: Optional[Text] = None) -> Text:
2905*8c35d5eeSXin Li  ...
2906*8c35d5eeSXin Lidef multiple_nullable_union(a: Union[None, Text, int]) -> Text
2907*8c35d5eeSXin Li  ...
2908*8c35d5eeSXin Li```
2909*8c35d5eeSXin Li
2910*8c35d5eeSXin Li```python
2911*8c35d5eeSXin LiNo:
2912*8c35d5eeSXin Lidef nullable_union(a: Union[None, Text]) -> Text:
2913*8c35d5eeSXin Li  ...
2914*8c35d5eeSXin Lidef implicit_optional(a: Text = None) -> Text:
2915*8c35d5eeSXin Li  ...
2916*8c35d5eeSXin Li```
2917*8c35d5eeSXin Li
2918*8c35d5eeSXin Li<a id="s3.19.6-aliases"></a>
2919*8c35d5eeSXin Li<a id="3196-type-aliases"></a>
2920*8c35d5eeSXin Li<a id="typing-aliases"></a>
2921*8c35d5eeSXin Li
2922*8c35d5eeSXin Li<a id="type-aliases"></a>
2923*8c35d5eeSXin Li#### 3.19.6 Type Aliases
2924*8c35d5eeSXin Li
2925*8c35d5eeSXin LiYou can declare aliases of complex types. The name of an alias should be
2926*8c35d5eeSXin LiCapWorded. If the alias is used only in this module, it should be
2927*8c35d5eeSXin Li\_Private.
2928*8c35d5eeSXin Li
2929*8c35d5eeSXin LiFor example, if the name of the module together with the name of the type is too
2930*8c35d5eeSXin Lilong:
2931*8c35d5eeSXin Li
2932*8c35d5eeSXin Li```python
2933*8c35d5eeSXin Li_ShortName = module_with_long_name.TypeWithLongName
2934*8c35d5eeSXin LiComplexMap = Mapping[Text, List[Tuple[int, int]]]
2935*8c35d5eeSXin Li```
2936*8c35d5eeSXin Li
2937*8c35d5eeSXin LiOther examples are complex nested types and multiple return variables from a
2938*8c35d5eeSXin Lifunction (as a tuple).
2939*8c35d5eeSXin Li
2940*8c35d5eeSXin Li<a id="s3.19.7-ignore"></a>
2941*8c35d5eeSXin Li<a id="3197-ignoring-types"></a>
2942*8c35d5eeSXin Li
2943*8c35d5eeSXin Li<a id="typing-ignore"></a>
2944*8c35d5eeSXin Li#### 3.19.7 Ignoring Types
2945*8c35d5eeSXin Li
2946*8c35d5eeSXin LiYou can disable type checking on a line with the special comment
2947*8c35d5eeSXin Li`# type: ignore`.
2948*8c35d5eeSXin Li
2949*8c35d5eeSXin Li`pytype` has a disable option for specific errors (similar to lint):
2950*8c35d5eeSXin Li
2951*8c35d5eeSXin Li```python
2952*8c35d5eeSXin Li# pytype: disable=attribute-error
2953*8c35d5eeSXin Li```
2954*8c35d5eeSXin Li
2955*8c35d5eeSXin Li<a id="s3.19.8-comments"></a>
2956*8c35d5eeSXin Li<a id="3198-typing-internal-variables"></a>
2957*8c35d5eeSXin Li
2958*8c35d5eeSXin Li<a id="typing-variables"></a>
2959*8c35d5eeSXin Li#### 3.19.8 Typing Variables
2960*8c35d5eeSXin Li
2961*8c35d5eeSXin LiIf an internal variable has a type that is hard or impossible to infer, you can
2962*8c35d5eeSXin Lispecify its type in a couple ways.
2963*8c35d5eeSXin Li
2964*8c35d5eeSXin Li<a id="type-comments"></a>
2965*8c35d5eeSXin Li[*Type Comments:*](#type-comments)
2966*8c35d5eeSXin Li:   Use a `# type:` comment on the end of the line
2967*8c35d5eeSXin Li
2968*8c35d5eeSXin Li    ```python
2969*8c35d5eeSXin Li    a = SomeUndecoratedFunction()  # type: Foo
2970*8c35d5eeSXin Li    ```
2971*8c35d5eeSXin Li
2972*8c35d5eeSXin Li[*Annotated Assignments*](#annotated-assignments)
2973*8c35d5eeSXin Li:   Use a colon and type between the variable name and value, as with function
2974*8c35d5eeSXin Li    arguments.
2975*8c35d5eeSXin Li
2976*8c35d5eeSXin Li    ```python
2977*8c35d5eeSXin Li    a: Foo = SomeUndecoratedFunction()
2978*8c35d5eeSXin Li    ```
2979*8c35d5eeSXin Li
2980*8c35d5eeSXin Li<a id="s3.19.9-tuples"></a>
2981*8c35d5eeSXin Li<a id="3199-tuples-vs-lists"></a>
2982*8c35d5eeSXin Li
2983*8c35d5eeSXin Li<a id="typing-tuples"></a>
2984*8c35d5eeSXin Li#### 3.19.9 Tuples vs Lists
2985*8c35d5eeSXin Li
2986*8c35d5eeSXin LiUnlike Lists, which can only have a single type, Tuples can have either a single
2987*8c35d5eeSXin Lirepeated type or a set number of elements with different types. The latter is
2988*8c35d5eeSXin Licommonly used as return type from a function.
2989*8c35d5eeSXin Li
2990*8c35d5eeSXin Li```python
2991*8c35d5eeSXin Lia = [1, 2, 3]  # type: List[int]
2992*8c35d5eeSXin Lib = (1, 2, 3)  # type: Tuple[int, ...]
2993*8c35d5eeSXin Lic = (1, "2", 3.5)  # type: Tuple[int, Text, float]
2994*8c35d5eeSXin Li```
2995*8c35d5eeSXin Li
2996*8c35d5eeSXin Li<a id="s3.19.10-type-var"></a>
2997*8c35d5eeSXin Li<a id="31910-typevar"></a>
2998*8c35d5eeSXin Li<a id="typing-type-var"></a>
2999*8c35d5eeSXin Li
3000*8c35d5eeSXin Li<a id="typevars"></a>
3001*8c35d5eeSXin Li#### 3.19.10 TypeVars
3002*8c35d5eeSXin Li
3003*8c35d5eeSXin LiThe Python type system has
3004*8c35d5eeSXin Li[generics](https://www.python.org/dev/peps/pep-0484/#generics). The factory
3005*8c35d5eeSXin Lifunction `TypeVar` is a common way to use them.
3006*8c35d5eeSXin Li
3007*8c35d5eeSXin LiExample:
3008*8c35d5eeSXin Li
3009*8c35d5eeSXin Li```python
3010*8c35d5eeSXin Lifrom typing import List, TypeVar
3011*8c35d5eeSXin LiT = TypeVar("T")
3012*8c35d5eeSXin Li...
3013*8c35d5eeSXin Lidef next(l: List[T]) -> T:
3014*8c35d5eeSXin Li  return l.pop()
3015*8c35d5eeSXin Li```
3016*8c35d5eeSXin Li
3017*8c35d5eeSXin LiA TypeVar can be constrained:
3018*8c35d5eeSXin Li
3019*8c35d5eeSXin Li```python
3020*8c35d5eeSXin LiAddableType = TypeVar("AddableType", int, float, Text)
3021*8c35d5eeSXin Lidef add(a: AddableType, b: AddableType) -> AddableType:
3022*8c35d5eeSXin Li  return a + b
3023*8c35d5eeSXin Li```
3024*8c35d5eeSXin Li
3025*8c35d5eeSXin LiA common predefined type variable in the `typing` module is `AnyStr`. Use it for
3026*8c35d5eeSXin Limultiple annotations that can be `bytes` or `unicode` and must all be the same
3027*8c35d5eeSXin Litype.
3028*8c35d5eeSXin Li
3029*8c35d5eeSXin Li```python
3030*8c35d5eeSXin Lifrom typing import AnyStr
3031*8c35d5eeSXin Lidef check_length(x: AnyStr) -> AnyStr:
3032*8c35d5eeSXin Li  if len(x) <= 42:
3033*8c35d5eeSXin Li    return x
3034*8c35d5eeSXin Li  raise ValueError()
3035*8c35d5eeSXin Li```
3036*8c35d5eeSXin Li
3037*8c35d5eeSXin Li<a id="s3.19.11-strings"></a>
3038*8c35d5eeSXin Li<a id="31911-string-types"></a>
3039*8c35d5eeSXin Li
3040*8c35d5eeSXin Li<a id="typing-strings"></a>
3041*8c35d5eeSXin Li#### 3.19.11 String types
3042*8c35d5eeSXin Li
3043*8c35d5eeSXin LiThe proper type for annotating strings depends on what versions of Python the
3044*8c35d5eeSXin Licode is intended for.
3045*8c35d5eeSXin Li
3046*8c35d5eeSXin LiFor Python 3 only code, prefer to use `str`. `Text` is also acceptable. Be
3047*8c35d5eeSXin Liconsistent in using one or the other.
3048*8c35d5eeSXin Li
3049*8c35d5eeSXin LiFor Python 2 compatible code, use `Text`. In some rare cases, `str` may make
3050*8c35d5eeSXin Lisense; typically to aid compatibility when the return types aren't the same
3051*8c35d5eeSXin Libetween the two Python versions. Avoid using `unicode`: it doesn't exist in
3052*8c35d5eeSXin LiPython 3.
3053*8c35d5eeSXin Li
3054*8c35d5eeSXin LiThe reason this discrepancy exists is because `str` means different things
3055*8c35d5eeSXin Lidepending on the Python version.
3056*8c35d5eeSXin Li
3057*8c35d5eeSXin Li```python
3058*8c35d5eeSXin LiNo:
3059*8c35d5eeSXin Lidef py2_code(x: str) -> unicode:
3060*8c35d5eeSXin Li  ...
3061*8c35d5eeSXin Li```
3062*8c35d5eeSXin Li
3063*8c35d5eeSXin LiFor code that deals with binary data, use `bytes`.
3064*8c35d5eeSXin Li
3065*8c35d5eeSXin Li```python
3066*8c35d5eeSXin Lidef deals_with_binary_data(x: bytes) -> bytes:
3067*8c35d5eeSXin Li  ...
3068*8c35d5eeSXin Li```
3069*8c35d5eeSXin Li
3070*8c35d5eeSXin LiFor Python 2 compatible code that processes text data (`str` or `unicode` in
3071*8c35d5eeSXin LiPython 2, `str` in Python 3), use `Text`. For Python 3 only code that process
3072*8c35d5eeSXin Litext data, prefer `str`.
3073*8c35d5eeSXin Li
3074*8c35d5eeSXin Li```python
3075*8c35d5eeSXin Lifrom typing import Text
3076*8c35d5eeSXin Li...
3077*8c35d5eeSXin Lidef py2_compatible(x: Text) -> Text:
3078*8c35d5eeSXin Li  ...
3079*8c35d5eeSXin Lidef py3_only(x: str) -> str:
3080*8c35d5eeSXin Li  ...
3081*8c35d5eeSXin Li```
3082*8c35d5eeSXin Li
3083*8c35d5eeSXin LiIf the type can be either bytes or text, use `Union`, with the appropriate text
3084*8c35d5eeSXin Litype.
3085*8c35d5eeSXin Li
3086*8c35d5eeSXin Li```python
3087*8c35d5eeSXin Lifrom typing import Text, Union
3088*8c35d5eeSXin Li...
3089*8c35d5eeSXin Lidef py2_compatible(x: Union[bytes, Text]) -> Union[bytes, Text]:
3090*8c35d5eeSXin Li  ...
3091*8c35d5eeSXin Lidef py3_only(x: Union[bytes, str]) -> Union[bytes, str]:
3092*8c35d5eeSXin Li  ...
3093*8c35d5eeSXin Li```
3094*8c35d5eeSXin Li
3095*8c35d5eeSXin LiIf all the string types of a function are always the same, for example if the
3096*8c35d5eeSXin Lireturn type is the same as the argument type in the code above, use
3097*8c35d5eeSXin Li[AnyStr](#typing-type-var).
3098*8c35d5eeSXin Li
3099*8c35d5eeSXin LiWriting it like this will simplify the process of porting the code to Python 3.
3100*8c35d5eeSXin Li
3101*8c35d5eeSXin Li<a id="s3.19.12-imports"></a>
3102*8c35d5eeSXin Li<a id="31912-imports-for-typing"></a>
3103*8c35d5eeSXin Li
3104*8c35d5eeSXin Li<a id="typing-imports"></a>
3105*8c35d5eeSXin Li#### 3.19.12 Imports For Typing
3106*8c35d5eeSXin Li
3107*8c35d5eeSXin LiFor classes from the `typing` module, always import the class itself. You are
3108*8c35d5eeSXin Liexplicitly allowed to import multiple specific classes on one line from the
3109*8c35d5eeSXin Li`typing` module. Ex:
3110*8c35d5eeSXin Li
3111*8c35d5eeSXin Li```python
3112*8c35d5eeSXin Lifrom typing import Any, Dict, Optional
3113*8c35d5eeSXin Li```
3114*8c35d5eeSXin Li
3115*8c35d5eeSXin LiGiven that this way of importing from `typing` adds items to the local
3116*8c35d5eeSXin Linamespace, any names in `typing` should be treated similarly to keywords, and
3117*8c35d5eeSXin Linot be defined in your Python code, typed or not. If there is a collision
3118*8c35d5eeSXin Libetween a type and an existing name in a module, import it using
3119*8c35d5eeSXin Li`import x as y`.
3120*8c35d5eeSXin Li
3121*8c35d5eeSXin Li```python
3122*8c35d5eeSXin Lifrom typing import Any as AnyType
3123*8c35d5eeSXin Li```
3124*8c35d5eeSXin Li
3125*8c35d5eeSXin Li<a id="s3.19.13-conditional-imports"></a>
3126*8c35d5eeSXin Li<a id="31913-conditional-imports"></a>
3127*8c35d5eeSXin Li
3128*8c35d5eeSXin Li<a id="typing-conditional-imports"></a>
3129*8c35d5eeSXin Li#### 3.19.13 Conditional Imports
3130*8c35d5eeSXin Li
3131*8c35d5eeSXin LiUse conditional imports only in exceptional cases where the additional imports
3132*8c35d5eeSXin Lineeded for type checking must be avoided at runtime. This pattern is
3133*8c35d5eeSXin Lidiscouraged; alternatives such as refactoring the code to allow top level
3134*8c35d5eeSXin Liimports should be preferred.
3135*8c35d5eeSXin Li
3136*8c35d5eeSXin LiImports that are needed only for type annotations can be placed within an
3137*8c35d5eeSXin Li`if TYPE_CHECKING:` block.
3138*8c35d5eeSXin Li
3139*8c35d5eeSXin Li-   Conditionally imported types need to be referenced as strings, to be
3140*8c35d5eeSXin Li    forward compatible with Python 3.6 where the annotation expressions are
3141*8c35d5eeSXin Li    actually evaluated.
3142*8c35d5eeSXin Li-   Only entities that are used solely for typing should be defined here; this
3143*8c35d5eeSXin Li    includes aliases. Otherwise it will be a runtime error, as the module will
3144*8c35d5eeSXin Li    not be imported at runtime.
3145*8c35d5eeSXin Li-   The block should be right after all the normal imports.
3146*8c35d5eeSXin Li-   There should be no empty lines in the typing imports list.
3147*8c35d5eeSXin Li-   Sort this list as if it were a regular imports list.
3148*8c35d5eeSXin Li
3149*8c35d5eeSXin Li```python
3150*8c35d5eeSXin Liimport typing
3151*8c35d5eeSXin Liif typing.TYPE_CHECKING:
3152*8c35d5eeSXin Li  import sketch
3153*8c35d5eeSXin Lidef f(x: "sketch.Sketch"): ...
3154*8c35d5eeSXin Li```
3155*8c35d5eeSXin Li
3156*8c35d5eeSXin Li<a id="s3.19.14-circular-deps"></a>
3157*8c35d5eeSXin Li<a id="31914-circular-dependencies"></a>
3158*8c35d5eeSXin Li
3159*8c35d5eeSXin Li<a id="typing-circular-deps"></a>
3160*8c35d5eeSXin Li#### 3.19.14 Circular Dependencies
3161*8c35d5eeSXin Li
3162*8c35d5eeSXin LiCircular dependencies that are caused by typing are code smells. Such code is a
3163*8c35d5eeSXin Ligood candidate for refactoring. Although technically it is possible to keep
3164*8c35d5eeSXin Licircular dependencies, the [build system](#typing-build-deps) will not let you
3165*8c35d5eeSXin Lido so because each module has to depend on the other.
3166*8c35d5eeSXin Li
3167*8c35d5eeSXin LiReplace modules that create circular dependency imports with `Any`. Set an
3168*8c35d5eeSXin Li[alias](#typing-aliases) with a meaningful name, and use the real type name from
3169*8c35d5eeSXin Lithis module (any attribute of Any is Any). Alias definitions should be separated
3170*8c35d5eeSXin Lifrom the last import by one line.
3171*8c35d5eeSXin Li
3172*8c35d5eeSXin Li```python
3173*8c35d5eeSXin Lifrom typing import Any
3174*8c35d5eeSXin Li
3175*8c35d5eeSXin Lisome_mod = Any  # some_mod.py imports this module.
3176*8c35d5eeSXin Li...
3177*8c35d5eeSXin Li
3178*8c35d5eeSXin Lidef my_method(self, var: some_mod.SomeType) -> None:
3179*8c35d5eeSXin Li  ...
3180*8c35d5eeSXin Li```
3181*8c35d5eeSXin Li
3182*8c35d5eeSXin Li<a id="typing-generics"></a>
3183*8c35d5eeSXin Li<a id="s3.19.15-generics"></a>
3184*8c35d5eeSXin Li<a id="31915-generics"></a>
3185*8c35d5eeSXin Li
3186*8c35d5eeSXin Li<a id="generics"></a>
3187*8c35d5eeSXin Li#### 3.19.15 Generics
3188*8c35d5eeSXin Li
3189*8c35d5eeSXin LiWhen annotating, prefer to specify type parameters for generic types; otherwise,
3190*8c35d5eeSXin Li[the generics' parameters will be assumed to be `Any`](https://www.python.org/dev/peps/pep-0484/#the-any-type).
3191*8c35d5eeSXin Li
3192*8c35d5eeSXin Li```python
3193*8c35d5eeSXin Lidef get_names(employee_ids: List[int]) -> Dict[int, Any]:
3194*8c35d5eeSXin Li  ...
3195*8c35d5eeSXin Li```
3196*8c35d5eeSXin Li
3197*8c35d5eeSXin Li```python
3198*8c35d5eeSXin Li# These are both interpreted as get_names(employee_ids: List[Any]) -> Dict[Any, Any]
3199*8c35d5eeSXin Lidef get_names(employee_ids: list) -> Dict:
3200*8c35d5eeSXin Li  ...
3201*8c35d5eeSXin Li
3202*8c35d5eeSXin Lidef get_names(employee_ids: List) -> Dict:
3203*8c35d5eeSXin Li  ...
3204*8c35d5eeSXin Li```
3205*8c35d5eeSXin Li
3206*8c35d5eeSXin LiIf the best type parameter for a generic is `Any`, make it explicit, but
3207*8c35d5eeSXin Liremember that in many cases [`TypeVar`](#typing-type-var) might be more
3208*8c35d5eeSXin Liappropriate:
3209*8c35d5eeSXin Li
3210*8c35d5eeSXin Li```python
3211*8c35d5eeSXin Lidef get_names(employee_ids: List[Any]) -> Dict[Any, Text]:
3212*8c35d5eeSXin Li  """Returns a mapping from employee ID to employee name for given IDs."""
3213*8c35d5eeSXin Li```
3214*8c35d5eeSXin Li
3215*8c35d5eeSXin Li```python
3216*8c35d5eeSXin LiT = TypeVar('T')
3217*8c35d5eeSXin Lidef get_names(employee_ids: List[T]) -> Dict[T, Text]:
3218*8c35d5eeSXin Li  """Returns a mapping from employee ID to employee name for given IDs."""
3219*8c35d5eeSXin Li```
3220*8c35d5eeSXin Li
3221*8c35d5eeSXin Li
3222*8c35d5eeSXin Li<a id="4-parting-words"></a>
3223*8c35d5eeSXin Li
3224*8c35d5eeSXin Li<a id="consistency"></a>
3225*8c35d5eeSXin Li## 4 Parting Words
3226*8c35d5eeSXin Li
3227*8c35d5eeSXin Li*BE CONSISTENT*.
3228*8c35d5eeSXin Li
3229*8c35d5eeSXin LiIf you're editing code, take a few minutes to look at the code around you and
3230*8c35d5eeSXin Lidetermine its style. If they use spaces around all their arithmetic operators,
3231*8c35d5eeSXin Liyou should too. If their comments have little boxes of hash marks around them,
3232*8c35d5eeSXin Limake your comments have little boxes of hash marks around them too.
3233*8c35d5eeSXin Li
3234*8c35d5eeSXin LiThe point of having style guidelines is to have a common vocabulary of coding so
3235*8c35d5eeSXin Lipeople can concentrate on what you're saying rather than on how you're saying
3236*8c35d5eeSXin Liit. We present global style rules here so people know the vocabulary, but local
3237*8c35d5eeSXin Listyle is also important. If code you add to a file looks drastically different
3238*8c35d5eeSXin Lifrom the existing code around it, it throws readers out of their rhythm when
3239*8c35d5eeSXin Lithey go to read it. Avoid this.
3240*8c35d5eeSXin Li
3241*8c35d5eeSXin Li
3242