blob: 5d9938c6c29458775c3e87041966cfcc4a102c6a [file] [log] [blame] [view]
Google Python teamcfce3c32018-02-05 15:51:47 -05001<!--
2AUTHORS:
3Prefer only GitHub-flavored Markdown in external text.
4See README.md for details.
5-->
6
7# Google Python Style Guide
8
9
Google Python team83a9e8d2019-10-10 00:40:18 -070010<a id="1-background"></a>
11
Google Python teamcfce3c32018-02-05 15:51:47 -050012<a id="background"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -070013## 1 Background
Google Python teamcfce3c32018-02-05 15:51:47 -050014
15Python is the main dynamic language used at Google. This style guide is a list
16of *dos and don'ts* for Python programs.
17
18To help you format code correctly, we've created a [settings file for
19Vim](google_python_style.vim). For Emacs, the default settings should be fine.
20
21Many teams use the [yapf](https://github.com/google/yapf/)
22auto-formatter to avoid arguing over formatting.
23
24
25<a id="s2-python-language-rules"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -070026<a id="2-python-language-rules"></a>
27
Google Python teamcfce3c32018-02-05 15:51:47 -050028<a id="python-language-rules"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -070029## 2 Python Language Rules
Google Python teamcfce3c32018-02-05 15:51:47 -050030
31<a id="s2.1-lint"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -070032<a id="21-lint"></a>
33
Google Python teamcfce3c32018-02-05 15:51:47 -050034<a id="lint"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -070035### 2.1 Lint
Google Python teamcfce3c32018-02-05 15:51:47 -050036
37Run `pylint` over your code.
38
39<a id="s2.1.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -070040<a id="211-definition"></a>
41
42<a id="lint-definition"></a>
43#### 2.1.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -050044
45`pylint` is a tool for finding bugs and style problems in Python source
46code. It finds problems that are typically caught by a compiler for less dynamic
47languages like C and C++. Because of the dynamic nature of Python, some
48warnings may be incorrect; however, spurious warnings should be fairly
49infrequent.
50
51<a id="s2.1.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -070052<a id="212-pros"></a>
53
54<a id="lint-pros"></a>
55#### 2.1.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -050056
57Catches easy-to-miss errors like typos, using-vars-before-assignment, etc.
58
59<a id="s2.1.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -070060<a id="213-cons"></a>
61
62<a id="lint-cons"></a>
63#### 2.1.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -050064
65`pylint` isn't perfect. To take advantage of it, we'll need to sometimes: a)
66Write around it b) Suppress its warnings or c) Improve it.
67
68<a id="s2.1.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -070069<a id="214-decision"></a>
70
71<a id="lint-decision"></a>
72#### 2.1.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -050073
74Make sure you run `pylint` on your code.
75
76
77Suppress warnings if they are inappropriate so that other issues are not hidden.
78To suppress warnings, you can set a line-level comment:
79
Google Python team5b06d2d2018-11-18 18:21:51 -080080```python
Google Python teamcfce3c32018-02-05 15:51:47 -050081dict = 'something awful' # Bad Idea... pylint: disable=redefined-builtin
82```
83
84`pylint` warnings are each identified by symbolic name (`empty-docstring`)
85Google-specific warnings start with `g-`.
86
87If the reason for the suppression is not clear from the symbolic name, add an
88explanation.
89
90Suppressing in this way has the advantage that we can easily search for
91suppressions and revisit them.
92
93You can get a list of `pylint` warnings by doing:
94
95```shell
96pylint --list-msgs
97```
98
99To get more information on a particular message, use:
100
101```shell
102pylint --help-msg=C6409
103```
104
105Prefer `pylint: disable` to the deprecated older form `pylint: disable-msg`.
106
107Unused argument warnings can be suppressed by deleting the variables at the
108beginning of the function. Always include a comment explaining why you are
109deleting it. "Unused." is sufficient. For example:
110
Google Python team5b06d2d2018-11-18 18:21:51 -0800111```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500112def viking_cafe_order(spam, beans, eggs=None):
113 del beans, eggs # Unused by vikings.
114 return spam + spam + spam
115```
116
117Other common forms of suppressing this warning include using '`_`' as the
118identifier for the unused argument, prefixing the argument name with
119'`unused_`', or assigning them to '`_`'. These forms are allowed but no longer
120encouraged. The first two break callers that pass arguments by name, while the
Google Python teamad22a752018-11-15 07:47:37 -0800121last does not enforce that the arguments are actually unused.
Google Python teamcfce3c32018-02-05 15:51:47 -0500122
123<a id="s2.2-imports"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700124<a id="22-imports"></a>
125
Google Python teamcfce3c32018-02-05 15:51:47 -0500126<a id="imports"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700127### 2.2 Imports
Google Python teamcfce3c32018-02-05 15:51:47 -0500128
Google Python team6271f3f2018-12-05 14:40:50 -0800129Use `import` statements for packages and modules only, not for individual
130classes or functions. Note that there is an explicit exemption for imports from
131the [typing module](#typing-imports).
Google Python teamcfce3c32018-02-05 15:51:47 -0500132
133<a id="s2.2.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700134<a id="221-definition"></a>
135
136<a id="imports-definition"></a>
137#### 2.2.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500138
139Reusability mechanism for sharing code from one module to another.
140
141<a id="s2.2.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700142<a id="222-pros"></a>
143
144<a id="imports-pros"></a>
145#### 2.2.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500146
147The namespace management convention is simple. The source of each identifier is
148indicated in a consistent way; `x.Obj` says that object `Obj` is defined in
149module `x`.
150
151<a id="s2.2.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700152<a id="223-cons"></a>
153
154<a id="imports-cons"></a>
155#### 2.2.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500156
157Module names can still collide. Some module names are inconveniently long.
158
159<a id="s2.2.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700160<a id="224-decision"></a>
161
162<a id="imports-decision"></a>
163#### 2.2.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500164
165* Use `import x` for importing packages and modules.
166* Use `from x import y` where `x` is the package prefix and `y` is the module
167name with no prefix.
168* Use `from x import y as z` if two modules named `y` are to be imported or if
169`y` is an inconveniently long name.
170* Use `import y as z` only when `z` is a standard abbreviation (e.g., `np` for
171`numpy`).
172
173For example the module `sound.effects.echo` may be imported as follows:
174
Google Python team5b06d2d2018-11-18 18:21:51 -0800175```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500176from sound.effects import echo
177...
178echo.EchoFilter(input, output, delay=0.7, atten=4)
179```
180
181Do not use relative names in imports. Even if the module is in the same package,
182use the full package name. This helps prevent unintentionally importing a
183package twice.
184
Google Python team83a9e8d2019-10-10 00:40:18 -0700185Imports from the [typing module](#typing-imports) and the
186[six.moves module](https://six.readthedocs.io/#module-six.moves)
187are exempt from this rule.
Google Python teamcfce3c32018-02-05 15:51:47 -0500188
189<a id="s2.3-packages"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700190<a id="23-packages"></a>
191
Google Python teamcfce3c32018-02-05 15:51:47 -0500192<a id="packages"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700193### 2.3 Packages
Google Python teamcfce3c32018-02-05 15:51:47 -0500194
195Import each module using the full pathname location of the module.
196
197<a id="s2.3.1-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700198<a id="231-pros"></a>
199
200<a id="packages-pros"></a>
201#### 2.3.1 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500202
Google Python teamfdc20e82018-11-28 10:15:08 -0800203Avoids conflicts in module names or incorrect imports due to the module search
204path not being what the author expected. Makes it easier to find modules.
Google Python teamcfce3c32018-02-05 15:51:47 -0500205
Google Python team83a9e8d2019-10-10 00:40:18 -0700206<a id="s2.3.2-cons"></a>
207<a id="232-cons"></a>
208
209<a id="packages-cons"></a>
210#### 2.3.2 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500211
212Makes it harder to deploy code because you have to replicate the package
Google Python teamfdc20e82018-11-28 10:15:08 -0800213hierarchy. Not really a problem with modern deployment mechanisms.
Google Python teamcfce3c32018-02-05 15:51:47 -0500214
215<a id="s2.3.3-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700216<a id="233-decision"></a>
217
218<a id="packages-decision"></a>
219#### 2.3.3 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500220
221All new code should import each module by its full package name.
222
223Imports should be as follows:
224
Google Python teamfdc20e82018-11-28 10:15:08 -0800225Yes:
Google Python teamcfce3c32018-02-05 15:51:47 -0500226
Google Python teamfdc20e82018-11-28 10:15:08 -0800227```python
228# Reference absl.flags in code with the complete name (verbose).
229import absl.flags
230from doctor.who import jodie
231
232FLAGS = absl.flags.FLAGS
Google Python teamcfce3c32018-02-05 15:51:47 -0500233```
234
Google Python teamfdc20e82018-11-28 10:15:08 -0800235```python
236# Reference flags in code with just the module name (common).
237from absl import flags
238from doctor.who import jodie
239
240FLAGS = flags.FLAGS
241```
242
243No: _(assume this file lives in `doctor/who/` where `jodie.py` also exists)_
244
245```python
246# Unclear what module the author wanted and what will be imported. The actual
247# import behavior depends on external factors controlling sys.path.
248# Which possible jodie module did the author intend to import?
249import jodie
250```
251
252The directory the main binary is located in should not be assumed to be in
253`sys.path` despite that happening in some environments. This being the case,
254code should assume that `import jodie` refers to a third party or top level
255package named `jodie`, not a local `jodie.py`.
256
Google Python team83a9e8d2019-10-10 00:40:18 -0700257
Google Python teamcfce3c32018-02-05 15:51:47 -0500258<a id="s2.4-exceptions"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700259<a id="24-exceptions"></a>
260
Google Python teamcfce3c32018-02-05 15:51:47 -0500261<a id="exceptions"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700262### 2.4 Exceptions
Google Python teamcfce3c32018-02-05 15:51:47 -0500263
264Exceptions are allowed but must be used carefully.
265
266<a id="s2.4.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700267<a id="241-definition"></a>
268
269<a id="exceptions-definition"></a>
270#### 2.4.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500271
272Exceptions are a means of breaking out of the normal flow of control of a code
273block to handle errors or other exceptional conditions.
274
275<a id="s2.4.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700276<a id="242-pros"></a>
277
278<a id="exceptions-pros"></a>
279#### 2.4.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500280
281The control flow of normal operation code is not cluttered by error-handling
282code. It also allows the control flow to skip multiple frames when a certain
283condition occurs, e.g., returning from N nested functions in one step instead of
284having to carry-through error codes.
285
286<a id="s2.4.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700287<a id="243-cons"></a>
288
289<a id="exceptions-cons"></a>
290#### 2.4.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500291
292May cause the control flow to be confusing. Easy to miss error cases when making
293library calls.
294
295<a id="s2.4.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700296<a id="244-decision"></a>
297
298<a id="exceptions-decision"></a>
299#### 2.4.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500300
301Exceptions must follow certain conditions:
302
303- Raise exceptions like this: `raise MyError('Error message')` or `raise
304 MyError()`. Do not use the two-argument form (`raise MyError, 'Error
305 message'`).
306
307- Make use of built-in exception classes when it makes sense. For example,
Google Python team83a9e8d2019-10-10 00:40:18 -0700308 raise a `ValueError` to indicate a programming mistake like a violated
309 precondition (such as if you were passed a negative number but required a
310 positive one). Do not use `assert` statements for validating argument values
311 of a public API. `assert` is used to ensure internal correctness, not to
312 enforce correct usage nor to indicate that some unexpected event occurred.
313 If an exception is desired in the latter cases, use a raise statement. For
314 example:
Google Python teamcfce3c32018-02-05 15:51:47 -0500315
316
Google Python team5b06d2d2018-11-18 18:21:51 -0800317 ```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500318 Yes:
Google Python teamad22a752018-11-15 07:47:37 -0800319 def connect_to_next_port(self, minimum):
320 """Connects to the next available port.
321
322 Args:
323 minimum: A port value greater or equal to 1024.
Google Python team83a9e8d2019-10-10 00:40:18 -0700324
Google Python teamad22a752018-11-15 07:47:37 -0800325 Returns:
326 The new minimum port.
Google Python team83a9e8d2019-10-10 00:40:18 -0700327
328 Raises:
329 ConnectionError: If no available port is found.
Google Python teamad22a752018-11-15 07:47:37 -0800330 """
331 if minimum < 1024:
Google Python team83a9e8d2019-10-10 00:40:18 -0700332 # Note that this raising of ValueError is not mentioned in the doc
333 # string's "Raises:" section because it is not appropriate to
334 # guarantee this specific behavioral reaction to API misuse.
Google Python teamad22a752018-11-15 07:47:37 -0800335 raise ValueError('Minimum port must be at least 1024, not %d.' % (minimum,))
336 port = self._find_next_open_port(minimum)
Google Python teamcfce3c32018-02-05 15:51:47 -0500337 if not port:
338 raise ConnectionError('Could not connect to service on %d or higher.' % (minimum,))
339 assert port >= minimum, 'Unexpected port %d when minimum was %d.' % (port, minimum)
340 return port
341 ```
342
Google Python team5b06d2d2018-11-18 18:21:51 -0800343 ```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500344 No:
Google Python teamad22a752018-11-15 07:47:37 -0800345 def connect_to_next_port(self, minimum):
346 """Connects to the next available port.
347
348 Args:
349 minimum: A port value greater or equal to 1024.
Google Python team83a9e8d2019-10-10 00:40:18 -0700350
Google Python teamad22a752018-11-15 07:47:37 -0800351 Returns:
352 The new minimum port.
353 """
354 assert minimum >= 1024, 'Minimum port must be at least 1024.'
355 port = self._find_next_open_port(minimum)
Google Python teamcfce3c32018-02-05 15:51:47 -0500356 assert port is not None
357 return port
358 ```
359
360- Libraries or packages may define their own exceptions. When doing so they
361 must inherit from an existing exception class. Exception names should end in
362 `Error` and should not introduce stutter (`foo.FooError`).
363
364- Never use catch-all `except:` statements, or catch `Exception` or
Google Python team83a9e8d2019-10-10 00:40:18 -0700365 `StandardError`, unless you are
366
367 - re-raising the exception, or
368 - creating an isolation point in the program where exceptions are not
369 propagated but are recorded and suppressed instead, such as protecting a
370 thread from crashing by guarding its outermost block.
371
372 Python is very tolerant in this regard and `except:` will really catch
373 everything including misspelled names, sys.exit() calls, Ctrl+C interrupts,
374 unittest failures and all kinds of other exceptions that you simply don't
375 want to catch.
Google Python teamcfce3c32018-02-05 15:51:47 -0500376
377- Minimize the amount of code in a `try`/`except` block. The larger the body
378 of the `try`, the more likely that an exception will be raised by a line of
379 code that you didn't expect to raise an exception. In those cases, the
380 `try`/`except` block hides a real error.
381
382- Use the `finally` clause to execute code whether or not an exception is
383 raised in the `try` block. This is often useful for cleanup, i.e., closing a
384 file.
385
386- When capturing an exception, use `as` rather than a comma. For example:
387
388
Google Python team5b06d2d2018-11-18 18:21:51 -0800389 ```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500390 try:
Google Python teamad22a752018-11-15 07:47:37 -0800391 raise Error()
Google Python teamcfce3c32018-02-05 15:51:47 -0500392 except Error as error:
393 pass
394 ```
395
396<a id="s2.5-global-variables"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700397<a id="25-global-variables"></a>
398
Google Python teamcfce3c32018-02-05 15:51:47 -0500399<a id="global-variables"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700400### 2.5 Global variables
Google Python teamcfce3c32018-02-05 15:51:47 -0500401
402Avoid global variables.
403
404<a id="s2.5.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700405<a id="251-definition"></a>
406
407<a id="global-variables-definition"></a>
408#### 2.5.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500409
410Variables that are declared at the module level or as class attributes.
411
412<a id="s2.5.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700413<a id="252-pros"></a>
414
415<a id="global-variables-pros"></a>
416#### 2.5.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500417
418Occasionally useful.
419
420<a id="s2.5.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700421<a id="253-cons"></a>
422
423<a id="global-variables-cons"></a>
424#### 2.5.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500425
426Has the potential to change module behavior during the import, because
427assignments to global variables are done when the module is first imported.
428
429<a id="s2.5.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700430<a id="254-decision"></a>
431
432<a id="global-variables-decision"></a>
433#### 2.5.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500434
435Avoid global variables.
436
437While they are technically variables, module-level constants are permitted and
438encouraged. For example: `MAX_HOLY_HANDGRENADE_COUNT = 3`. Constants must be
439named using all caps with underscores. See [Naming](#s3.16-naming) below.
440
441If needed, globals should be declared at the module level and made internal to
442the module by prepending an `_` to the name. External access must be done
443through public module-level functions. See [Naming](#s3.16-naming) below.
444
445<a id="s2.6-nested"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700446<a id="26-nested"></a>
447
448<a id="nested-classes-functions"></a>
449### 2.6 Nested/Local/Inner Classes and Functions
Google Python teamcfce3c32018-02-05 15:51:47 -0500450
451Nested local functions or classes are fine when used to close over a local
452variable. Inner classes are fine.
453
454<a id="s2.6.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700455<a id="261-definition"></a>
456
457<a id="nested-classes-functions-definition"></a>
458#### 2.6.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500459
460A class can be defined inside of a method, function, or class. A function can be
461defined inside a method or function. Nested functions have read-only access to
462variables defined in enclosing scopes.
463
464<a id="s2.6.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700465<a id="262-pros"></a>
466
467<a id="nested-classes-functions-pros"></a>
468#### 2.6.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500469
470Allows definition of utility classes and functions that are only used inside of
471a very limited scope. Very
472[ADT](http://www.google.com/url?sa=D&q=http://en.wikipedia.org/wiki/Abstract_data_type)-y.
Google Python teamad22a752018-11-15 07:47:37 -0800473Commonly used for implementing decorators.
Google Python teamcfce3c32018-02-05 15:51:47 -0500474
475<a id="s2.6.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700476<a id="263-cons"></a>
477
478<a id="nested-classes-functions-cons"></a>
479#### 2.6.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500480
481Instances of nested or local classes cannot be pickled. Nested functions and
482classes cannot be directly tested. Nesting can make your outer function longer
483and less readable.
484
485<a id="s2.6.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700486<a id="264-decision"></a>
487
488<a id="nested-classes-functions-decision"></a>
489#### 2.6.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500490
Google Python teamad22a752018-11-15 07:47:37 -0800491They are fine with some caveats. Avoid nested functions or classes except when
492closing over a local value. Do not nest a function just to hide it from users
493of a module. Instead, prefix its name with an \_ at the module level so that it
494can still be accessed by tests.
Google Python teamcfce3c32018-02-05 15:51:47 -0500495
Google Python teamcfce3c32018-02-05 15:51:47 -0500496<a id="s2.7-list_comprehensions"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700497<a id="27-list_comprehensions"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -0500498<a id="list_comprehensions"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700499<a id="list-comprehensions"></a>
500
501<a id="comprehensions"></a>
502### 2.7 Comprehensions & Generator Expressions
Google Python teamcfce3c32018-02-05 15:51:47 -0500503
504Okay to use for simple cases.
505
506<a id="s2.7.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700507<a id="271-definition"></a>
508
509<a id="comprehensions-definition"></a>
510#### 2.7.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500511
512List, Dict, and Set comprehensions as well as generator expressions provide a
513concise and efficient way to create container types and iterators without
514resorting to the use of traditional loops, `map()`, `filter()`, or `lambda`.
515
516<a id="s2.7.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700517<a id="272-pros"></a>
518
519<a id="comprehensions-pros"></a>
520#### 2.7.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500521
522Simple comprehensions can be clearer and simpler than other dict, list, or set
523creation techniques. Generator expressions can be very efficient, since they
524avoid the creation of a list entirely.
525
526<a id="s2.7.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700527<a id="273-cons"></a>
528
529<a id="comprehensions-cons"></a>
530#### 2.7.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500531
532Complicated comprehensions or generator expressions can be hard to read.
533
534<a id="s2.7.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700535<a id="274-decision"></a>
536
537<a id="comprehensions-decision"></a>
538#### 2.7.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500539
540Okay to use for simple cases. Each portion must fit on one line: mapping
541expression, `for` clause, filter expression. Multiple `for` clauses or filter
542expressions are not permitted. Use loops instead when things get more
543complicated.
544
Google Python team5b06d2d2018-11-18 18:21:51 -0800545```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500546Yes:
Google Python teamad22a752018-11-15 07:47:37 -0800547 result = [mapping_expr for value in iterable if filter_expr]
548
549 result = [{'key': value} for value in iterable
550 if a_long_filter_expression(value)]
551
552 result = [complicated_transform(x)
553 for x in iterable if predicate(x)]
554
555 descriptive_name = [
556 transform({'key': key, 'value': value}, color='black')
557 for key, value in generate_iterable(some_input)
558 if complicated_condition_is_met(key, value)
559 ]
560
Google Python teamcfce3c32018-02-05 15:51:47 -0500561 result = []
562 for x in range(10):
563 for y in range(5):
564 if x * y > 10:
565 result.append((x, y))
566
Google Python teamad22a752018-11-15 07:47:37 -0800567 return {x: complicated_transform(x)
Google Python teamcfce3c32018-02-05 15:51:47 -0500568 for x in long_generator_function(parameter)
Google Python teamad22a752018-11-15 07:47:37 -0800569 if x is not None}
Google Python teamcfce3c32018-02-05 15:51:47 -0500570
Google Python teamad22a752018-11-15 07:47:37 -0800571 squares_generator = (x**2 for x in range(10))
572
573 unique_names = {user.name for user in users if user is not None}
Google Python teamcfce3c32018-02-05 15:51:47 -0500574
575 eat(jelly_bean for jelly_bean in jelly_beans
576 if jelly_bean.color == 'black')
577```
578
Google Python team5b06d2d2018-11-18 18:21:51 -0800579```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500580No:
Google Python teamad22a752018-11-15 07:47:37 -0800581 result = [complicated_transform(
582 x, some_argument=x+1)
583 for x in iterable if predicate(x)]
584
Google Python teamcfce3c32018-02-05 15:51:47 -0500585 result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]
586
587 return ((x, y, z)
588 for x in xrange(5)
589 for y in xrange(5)
590 if x != y
591 for z in xrange(5)
592 if y != z)
593```
594
595<a id="s2.8-default-iterators-and-operators"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700596
597<a id="default-iterators-operators"></a>
598### 2.8 Default Iterators and Operators
Google Python teamcfce3c32018-02-05 15:51:47 -0500599
600Use default iterators and operators for types that support them, like lists,
601dictionaries, and files.
602
603<a id="s2.8.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700604<a id="281-definition"></a>
605
606<a id="default-iterators-operators-definition"></a>
607#### 2.8.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500608
609Container types, like dictionaries and lists, define default iterators and
610membership test operators ("in" and "not in").
611
612<a id="s2.8.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700613<a id="282-pros"></a>
614
615<a id="default-iterators-operators-pros"></a>
616#### 2.8.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500617
618The default iterators and operators are simple and efficient. They express the
619operation directly, without extra method calls. A function that uses default
620operators is generic. It can be used with any type that supports the operation.
621
622<a id="s2.8.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700623<a id="283-cons"></a>
624
625<a id="default-iterators-operators-cons"></a>
626#### 2.8.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500627
628You can't tell the type of objects by reading the method names (e.g. has\_key()
629means a dictionary). This is also an advantage.
630
631<a id="s2.8.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700632<a id="284-decision"></a>
633
634<a id="default-iterators-operators-decision"></a>
635#### 2.8.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500636
637Use default iterators and operators for types that support them, like lists,
638dictionaries, and files. The built-in types define iterator methods, too. Prefer
639these methods to methods that return lists, except that you should not mutate a
Google Python team6271f3f2018-12-05 14:40:50 -0800640container while iterating over it. Never use Python 2 specific iteration
641methods such as `dict.iter*()` unless necessary.
Google Python teamcfce3c32018-02-05 15:51:47 -0500642
Google Python team5b06d2d2018-11-18 18:21:51 -0800643```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500644Yes: for key in adict: ...
645 if key not in adict: ...
646 if obj in alist: ...
647 for line in afile: ...
Google Python team6271f3f2018-12-05 14:40:50 -0800648 for k, v in adict.items(): ...
649 for k, v in six.iteritems(adict): ...
Google Python teamcfce3c32018-02-05 15:51:47 -0500650```
651
Google Python team5b06d2d2018-11-18 18:21:51 -0800652```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500653No: for key in adict.keys(): ...
654 if not adict.has_key(key): ...
655 for line in afile.readlines(): ...
Google Python team6271f3f2018-12-05 14:40:50 -0800656 for k, v in dict.iteritems(): ...
Google Python teamcfce3c32018-02-05 15:51:47 -0500657```
658
659<a id="s2.9-generators"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700660<a id="29-generators"></a>
661
Google Python teamcfce3c32018-02-05 15:51:47 -0500662<a id="generators"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700663### 2.9 Generators
Google Python teamcfce3c32018-02-05 15:51:47 -0500664
665Use generators as needed.
666
darvid79ea26f72018-03-22 15:52:20 +1100667<a id="s2.9.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700668<a id="291-definition"></a>
669
670<a id="generators-definition"></a>
671#### 2.9 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500672
673A generator function returns an iterator that yields a value each time it
674executes a yield statement. After it yields a value, the runtime state of the
675generator function is suspended until the next value is needed.
676
darvid79ea26f72018-03-22 15:52:20 +1100677<a id="s2.9.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700678<a id="292-pros"></a>
679
680<a id="generators-pros"></a>
681#### 2.9.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500682
683Simpler code, because the state of local variables and control flow are
684preserved for each call. A generator uses less memory than a function that
685creates an entire list of values at once.
686
darvid79ea26f72018-03-22 15:52:20 +1100687<a id="s2.9.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700688<a id="293-cons"></a>
689
690<a id="generators-cons"></a>
691#### 2.9.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500692
693None.
694
darvid79ea26f72018-03-22 15:52:20 +1100695<a id="s2.9.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700696<a id="294-decision"></a>
697
698<a id="generators-decision"></a>
699#### 2.9.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500700
701Fine. Use "Yields:" rather than "Returns:" in the docstring for generator
702functions.
703
704<a id="s2.10-lambda-functions"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700705<a id="210-lambda-functions"></a>
706
707<a id="lambdas"></a>
708### 2.10 Lambda Functions
Google Python teamcfce3c32018-02-05 15:51:47 -0500709
710Okay for one-liners.
711
darvid79ea26f72018-03-22 15:52:20 +1100712<a id="s2.10.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700713<a id="2101-definition"></a>
714
715<a id="lambdas-definition"></a>
716#### 2.10.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500717
718Lambdas define anonymous functions in an expression, as opposed to a statement.
719They are often used to define callbacks or operators for higher-order functions
720like `map()` and `filter()`.
721
darvid79ea26f72018-03-22 15:52:20 +1100722<a id="s2.10.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700723<a id="2102-pros"></a>
724
725<a id="lambdas-pros"></a>
726#### 2.10.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500727
728Convenient.
729
darvid79ea26f72018-03-22 15:52:20 +1100730<a id="s2.10.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700731<a id="2103-cons"></a>
732
733<a id="lambdas-cons"></a>
734#### 2.10.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500735
736Harder to read and debug than local functions. The lack of names means stack
737traces are more difficult to understand. Expressiveness is limited because the
738function may only contain an expression.
739
darvid79ea26f72018-03-22 15:52:20 +1100740<a id="s2.10.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700741<a id="2104-decision"></a>
742
743<a id="lambdas-decision"></a>
744#### 2.10.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500745
Google Python team6271f3f2018-12-05 14:40:50 -0800746Okay to use them for one-liners. If the code inside the lambda function is
747longer than 60-80 chars, it's probably better to define it as a regular [nested
748function](#lexical-scoping).
Google Python teamcfce3c32018-02-05 15:51:47 -0500749
750For common operations like multiplication, use the functions from the `operator`
751module instead of lambda functions. For example, prefer `operator.mul` to
752`lambda x, y: x * y`.
753
754<a id="s2.11-conditional-expressions"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700755<a id="211-conditional-expressions"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -0500756
Google Python team83a9e8d2019-10-10 00:40:18 -0700757<a id="conditional-expressions"></a>
758### 2.11 Conditional Expressions
759
760Okay for simple cases.
Google Python teamcfce3c32018-02-05 15:51:47 -0500761
darvid79ea26f72018-03-22 15:52:20 +1100762<a id="s2.11.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700763<a id="2111-definition"></a>
764
765<a id="conditional-expressions-definition"></a>
766#### 2.11.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500767
768Conditional expressions (sometimes called a “ternary operator”) are mechanisms
769that provide a shorter syntax for if statements. For example:
770`x = 1 if cond else 2`.
771
darvid79ea26f72018-03-22 15:52:20 +1100772<a id="s2.11.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700773<a id="2112-pros"></a>
774
775<a id="conditional-expressions-pros"></a>
776#### 2.11.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500777
778Shorter and more convenient than an if statement.
779
darvid79ea26f72018-03-22 15:52:20 +1100780<a id="s2.11.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700781<a id="2113-cons"></a>
782
783<a id="conditional-expressions-cons"></a>
784#### 2.11.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500785
786May be harder to read than an if statement. The condition may be difficult to
787locate if the expression is long.
788
darvid79ea26f72018-03-22 15:52:20 +1100789<a id="s2.11.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700790<a id="2114-decision"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -0500791
Google Python team83a9e8d2019-10-10 00:40:18 -0700792<a id="conditional-expressions-decision"></a>
793#### 2.11.4 Decision
794
795Okay to use for simple cases. Each portion must fit on one line:
796true-expression, if-expression, else-expression. Use a complete if statement
797when things get more complicated.
798
799```python
800one_line = 'yes' if predicate(value) else 'no'
801slightly_split = ('yes' if predicate(value)
802 else 'no, nein, nyet')
803the_longest_ternary_style_that_can_be_done = (
804 'yes, true, affirmative, confirmed, correct'
805 if predicate(value)
806 else 'no, false, negative, nay')
807```
808
809```python
810bad_line_breaking = ('yes' if predicate(value) else
811 'no')
812portion_too_long = ('yes'
813 if some_long_module.some_long_predicate_function(
814 really_long_variable_name)
815 else 'no, false, negative, nay')
816```
Google Python teamcfce3c32018-02-05 15:51:47 -0500817
818<a id="s2.12-default-argument-values"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700819<a id="212-default-argument-values"></a>
820
821<a id="default-arguments"></a>
822### 2.12 Default Argument Values
Google Python teamcfce3c32018-02-05 15:51:47 -0500823
824Okay in most cases.
825
darvid79ea26f72018-03-22 15:52:20 +1100826<a id="s2.12.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700827<a id="2121-definition"></a>
828
829<a id="default-arguments-definition"></a>
830#### 2.12.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500831
832You can specify values for variables at the end of a function's parameter list,
833e.g., `def foo(a, b=0):`. If `foo` is called with only one argument,
834`b` is set to 0. If it is called with two arguments, `b` has the value of the
835second argument.
836
darvid79ea26f72018-03-22 15:52:20 +1100837<a id="s2.12.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700838<a id="2122-pros"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -0500839
Google Python team83a9e8d2019-10-10 00:40:18 -0700840<a id="default-arguments-pros"></a>
841#### 2.12.2 Pros
842
843Often you have a function that uses lots of default values, but on rare
844occasions you want to override the defaults. Default argument values provide an
845easy way to do this, without having to define lots of functions for the rare
846exceptions. As Python does not support overloaded methods/functions, default
847arguments are an easy way of "faking" the overloading behavior.
Google Python teamcfce3c32018-02-05 15:51:47 -0500848
darvid79ea26f72018-03-22 15:52:20 +1100849<a id="s2.12.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700850<a id="2123-cons"></a>
851
852<a id="default-arguments-cons"></a>
853#### 2.12.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500854
855Default arguments are evaluated once at module load time. This may cause
856problems if the argument is a mutable object such as a list or a dictionary. If
857the function modifies the object (e.g., by appending an item to a list), the
858default value is modified.
859
darvid79ea26f72018-03-22 15:52:20 +1100860<a id="s2.12.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700861<a id="2124-decision"></a>
862
863<a id="default-arguments-decision"></a>
864#### 2.12.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500865
866Okay to use with the following caveat:
867
868Do not use mutable objects as default values in the function or method
869definition.
870
Google Python team5b06d2d2018-11-18 18:21:51 -0800871```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500872Yes: def foo(a, b=None):
873 if b is None:
874 b = []
875Yes: def foo(a, b: Optional[Sequence] = None):
876 if b is None:
877 b = []
Google Python teamad22a752018-11-15 07:47:37 -0800878Yes: def foo(a, b: Sequence = ()): # Empty tuple OK since tuples are immutable
879 ...
Google Python teamcfce3c32018-02-05 15:51:47 -0500880```
881
Google Python team5b06d2d2018-11-18 18:21:51 -0800882```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500883No: def foo(a, b=[]):
884 ...
885No: def foo(a, b=time.time()): # The time the module was loaded???
886 ...
887No: def foo(a, b=FLAGS.my_thing): # sys.argv has not yet been parsed...
888 ...
889```
890
891<a id="s2.13-properties"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700892<a id="213-properties"></a>
893
Google Python teamcfce3c32018-02-05 15:51:47 -0500894<a id="properties"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700895### 2.13 Properties
Google Python teamcfce3c32018-02-05 15:51:47 -0500896
897Use properties for accessing or setting data where you would normally have used
898simple, lightweight accessor or setter methods.
899
darvid79ea26f72018-03-22 15:52:20 +1100900<a id="s2.13.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700901<a id="2131-definition"></a>
902
903<a id="properties-definition"></a>
904#### 2.13.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -0500905
906A way to wrap method calls for getting and setting an attribute as a standard
907attribute access when the computation is lightweight.
908
darvid79ea26f72018-03-22 15:52:20 +1100909<a id="s2.13.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700910<a id="2132-pros"></a>
911
912<a id="properties-pros"></a>
913#### 2.13.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -0500914
915Readability is increased by eliminating explicit get and set method calls for
916simple attribute access. Allows calculations to be lazy. Considered the Pythonic
917way to maintain the interface of a class. In terms of performance, allowing
918properties bypasses needing trivial accessor methods when a direct variable
919access is reasonable. This also allows accessor methods to be added in the
920future without breaking the interface.
921
darvid79ea26f72018-03-22 15:52:20 +1100922<a id="s2.13.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700923<a id="2133-cons"></a>
924
925<a id="properties-cons"></a>
926#### 2.13.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -0500927
928Must inherit from `object` in Python 2. Can hide side-effects much like operator
929overloading. Can be confusing for subclasses.
930
darvid79ea26f72018-03-22 15:52:20 +1100931<a id="s2.13.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700932<a id="2134-decision"></a>
933
934<a id="properties-decision"></a>
935#### 2.13.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -0500936
937Use properties in new code to access or set data where you would normally have
938used simple, lightweight accessor or setter methods. Properties should be
939created with the `@property` [decorator](#s2.17-function-and-method-decorators).
940
941Inheritance with properties can be non-obvious if the property itself is not
942overridden. Thus one must make sure that accessor methods are called indirectly
943to ensure methods overridden in subclasses are called by the property (using the
944Template Method DP).
945
Google Python team5b06d2d2018-11-18 18:21:51 -0800946```python
Google Python teamcfce3c32018-02-05 15:51:47 -0500947Yes: import math
948
949 class Square(object):
950 """A square with two properties: a writable area and a read-only perimeter.
951
952 To use:
953 >>> sq = Square(3)
954 >>> sq.area
955 9
956 >>> sq.perimeter
957 12
958 >>> sq.area = 16
959 >>> sq.side
960 4
961 >>> sq.perimeter
962 16
963 """
964
965 def __init__(self, side):
966 self.side = side
967
968 @property
969 def area(self):
Google Python team83a9e8d2019-10-10 00:40:18 -0700970 """Area of the square."""
Google Python teamcfce3c32018-02-05 15:51:47 -0500971 return self._get_area()
972
973 @area.setter
974 def area(self, area):
975 return self._set_area(area)
976
977 def _get_area(self):
978 """Indirect accessor to calculate the 'area' property."""
979 return self.side ** 2
980
981 def _set_area(self, area):
982 """Indirect setter to set the 'area' property."""
983 self.side = math.sqrt(area)
984
985 @property
986 def perimeter(self):
987 return self.side * 4
988```
989
990<a id="s2.14-truefalse-evaluations"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700991<a id="214-truefalse-evaluations"></a>
992
Google Python teamcfce3c32018-02-05 15:51:47 -0500993<a id="truefalse-evaluations"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700994### 2.14 True/False Evaluations
Google Python teamcfce3c32018-02-05 15:51:47 -0500995
996Use the "implicit" false if at all possible.
997
darvid79ea26f72018-03-22 15:52:20 +1100998<a id="s2.14.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -0700999<a id="2141-definition"></a>
1000
1001<a id="truefalse-evaluations-definition"></a>
1002#### 2.14.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -05001003
1004Python evaluates certain values as `False` when in a boolean context. A quick
1005"rule of thumb" is that all "empty" values are considered false, so
1006`0, None, [], {}, ''` all evaluate as false in a boolean context.
1007
darvid79ea26f72018-03-22 15:52:20 +11001008<a id="s2.14.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001009<a id="2142-pros"></a>
1010
1011<a id="truefalse-evaluations-pros"></a>
1012#### 2.14.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -05001013
1014Conditions using Python booleans are easier to read and less error-prone. In
1015most cases, they're also faster.
1016
darvid79ea26f72018-03-22 15:52:20 +11001017<a id="s2.14.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001018<a id="2143-cons"></a>
1019
1020<a id="truefalse-evaluations-cons"></a>
1021#### 2.14.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -05001022
1023May look strange to C/C++ developers.
1024
darvid79ea26f72018-03-22 15:52:20 +11001025<a id="s2.14.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001026<a id="2144-decision"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05001027
Google Python team83a9e8d2019-10-10 00:40:18 -07001028<a id="truefalse-evaluations-decision"></a>
1029#### 2.14.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -05001030
Google Python team83a9e8d2019-10-10 00:40:18 -07001031Use the "implicit" false if possible, e.g., `if foo:` rather than `if foo !=
1032[]:`. There are a few caveats that you should keep in mind though:
Google Python teamcfce3c32018-02-05 15:51:47 -05001033
Google Python team83a9e8d2019-10-10 00:40:18 -07001034- Always use `if foo is None:` (or `is not None`) to check for a `None`
1035 value-e.g., when testing whether a variable or argument that defaults to
1036 `None` was set to some other value. The other value might be a value that's
1037 false in a boolean context!
Google Python teamcfce3c32018-02-05 15:51:47 -05001038
1039- Never compare a boolean variable to `False` using `==`. Use `if not x:`
1040 instead. If you need to distinguish `False` from `None` then chain the
1041 expressions, such as `if not x and x is not None:`.
1042
1043- For sequences (strings, lists, tuples), use the fact that empty sequences
1044 are false, so `if seq:` and `if not seq:` are preferable to `if len(seq):`
1045 and `if not len(seq):` respectively.
1046
1047- When handling integers, implicit false may involve more risk than benefit
1048 (i.e., accidentally handling `None` as 0). You may compare a value which is
1049 known to be an integer (and is not the result of `len()`) against the
1050 integer 0.
1051
Google Python team5b06d2d2018-11-18 18:21:51 -08001052 ```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001053 Yes: if not users:
1054 print('no users')
1055
1056 if foo == 0:
1057 self.handle_zero()
1058
1059 if i % 10 == 0:
1060 self.handle_multiple_of_ten()
1061
1062 def f(x=None):
1063 if x is None:
1064 x = []
1065 ```
1066
Google Python team5b06d2d2018-11-18 18:21:51 -08001067 ```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001068 No: if len(users) == 0:
1069 print('no users')
1070
1071 if foo is not None and not foo:
1072 self.handle_zero()
1073
1074 if not i % 10:
1075 self.handle_multiple_of_ten()
1076
1077 def f(x=None):
1078 x = x or []
1079 ```
1080
1081- Note that `'0'` (i.e., `0` as string) evaluates to true.
1082
1083<a id="s2.15-deprecated-language-features"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001084<a id="215-deprecated-language-features"></a>
1085
1086<a id="deprecated-features"></a>
1087### 2.15 Deprecated Language Features
Google Python teamcfce3c32018-02-05 15:51:47 -05001088
1089Use string methods instead of the `string` module where possible. Use function
1090call syntax instead of `apply`. Use list comprehensions and `for` loops instead
1091of `filter` and `map` when the function argument would have been an inlined
1092lambda anyway. Use `for` loops instead of `reduce`.
1093
darvid79ea26f72018-03-22 15:52:20 +11001094<a id="s2.15.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001095<a id="2151-definition"></a>
1096
1097<a id="deprecated-features-definition"></a>
1098#### 2.15.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -05001099
1100Current versions of Python provide alternative constructs that people find
1101generally preferable.
1102
darvid79ea26f72018-03-22 15:52:20 +11001103<a id="s2.15.2-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001104<a id="2152-decision"></a>
1105
1106<a id="deprecated-features-decision"></a>
1107#### 2.15.2 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -05001108
1109We do not use any Python version which does not support these features, so there
1110is no reason not to use the new styles.
1111
Google Python team5b06d2d2018-11-18 18:21:51 -08001112```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001113Yes: words = foo.split(':')
1114
1115 [x[1] for x in my_list if x[2] == 5]
1116
1117 map(math.sqrt, data) # Ok. No inlined lambda expression.
1118
1119 fn(*args, **kwargs)
1120```
1121
Google Python team5b06d2d2018-11-18 18:21:51 -08001122```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001123No: words = string.split(foo, ':')
1124
1125 map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
1126
1127 apply(fn, args, kwargs)
1128```
1129
1130<a id="s2.16-lexical-scoping"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001131<a id="216-lexical-scoping"></a>
1132
Google Python teamcfce3c32018-02-05 15:51:47 -05001133<a id="lexical-scoping"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001134### 2.16 Lexical Scoping
Google Python teamcfce3c32018-02-05 15:51:47 -05001135
1136Okay to use.
1137
darvid79ea26f72018-03-22 15:52:20 +11001138<a id="s2.16.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001139<a id="2161-definition"></a>
1140
1141<a id="lexical-scoping-definition"></a>
1142#### 2.16.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -05001143
1144A nested Python function can refer to variables defined in enclosing functions,
1145but can not assign to them. Variable bindings are resolved using lexical
1146scoping, that is, based on the static program text. Any assignment to a name in
1147a block will cause Python to treat all references to that name as a local
1148variable, even if the use precedes the assignment. If a global declaration
1149occurs, the name is treated as a global variable.
1150
1151An example of the use of this feature is:
1152
Google Python team5b06d2d2018-11-18 18:21:51 -08001153```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001154def get_adder(summand1):
1155 """Returns a function that adds numbers to a given number."""
1156 def adder(summand2):
1157 return summand1 + summand2
1158
1159 return adder
1160```
1161
darvid79ea26f72018-03-22 15:52:20 +11001162<a id="s2.16.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001163<a id="2162-pros"></a>
1164
1165<a id="lexical-scoping-pros"></a>
1166#### 2.16.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -05001167
1168Often results in clearer, more elegant code. Especially comforting to
1169experienced Lisp and Scheme (and Haskell and ML and ...) programmers.
1170
darvid79ea26f72018-03-22 15:52:20 +11001171<a id="s2.16.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001172<a id="2163-cons"></a>
1173
1174<a id="lexical-scoping-cons"></a>
1175#### 2.16.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -05001176
1177Can lead to confusing bugs. Such as this example based on
1178[PEP-0227](http://www.google.com/url?sa=D&q=http://www.python.org/dev/peps/pep-0227/):
1179
Google Python team5b06d2d2018-11-18 18:21:51 -08001180```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001181i = 4
1182def foo(x):
1183 def bar():
1184 print(i, end='')
1185 # ...
1186 # A bunch of code here
1187 # ...
1188 for i in x: # Ah, i *is* local to foo, so this is what bar sees
1189 print(i, end='')
1190 bar()
1191```
1192
1193So `foo([1, 2, 3])` will print `1 2 3 3`, not `1 2 3
11944`.
1195
darvid79ea26f72018-03-22 15:52:20 +11001196<a id="s2.16.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001197<a id="2164-decision"></a>
1198
1199<a id="lexical-scoping-decision"></a>
1200#### 2.16.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -05001201
1202Okay to use.
1203
1204<a id="s2.17-function-and-method-decorators"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001205<a id="217-function-and-method-decorators"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05001206<a id="function-and-method-decorators"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001207
1208<a id="decorators"></a>
1209### 2.17 Function and Method Decorators
Google Python teamcfce3c32018-02-05 15:51:47 -05001210
1211Use decorators judiciously when there is a clear advantage. Avoid
1212`@staticmethod` and limit use of `@classmethod`.
1213
darvid79ea26f72018-03-22 15:52:20 +11001214<a id="s2.17.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001215<a id="2171-definition"></a>
1216
1217<a id="decorators-definition"></a>
1218#### 2.17.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -05001219
1220[Decorators for Functions and
Google Python teamad22a752018-11-15 07:47:37 -08001221Methods](https://docs.python.org/3/glossary.html#term-decorator)
Google Python teamcfce3c32018-02-05 15:51:47 -05001222(a.k.a "the `@` notation"). One common decorator is `@property`, used for
1223converting ordinary methods into dynamically computed attributes. However, the
1224decorator syntax allows for user-defined decorators as well. Specifically, for
1225some function `my_decorator`, this:
1226
Google Python team5b06d2d2018-11-18 18:21:51 -08001227```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001228class C(object):
1229 @my_decorator
1230 def method(self):
1231 # method body ...
1232```
1233
1234is equivalent to:
1235
Google Python teamad22a752018-11-15 07:47:37 -08001236
Google Python team5b06d2d2018-11-18 18:21:51 -08001237```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001238class C(object):
Google Python teamad22a752018-11-15 07:47:37 -08001239 def method(self):
Google Python teamcfce3c32018-02-05 15:51:47 -05001240 # method body ...
Google Python teamad22a752018-11-15 07:47:37 -08001241 method = my_decorator(method)
Google Python teamcfce3c32018-02-05 15:51:47 -05001242```
1243
darvid79ea26f72018-03-22 15:52:20 +11001244<a id="s2.17.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001245<a id="2172-pros"></a>
1246
1247<a id="decorators-pros"></a>
1248#### 2.17.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -05001249
1250Elegantly specifies some transformation on a method; the transformation might
1251eliminate some repetitive code, enforce invariants, etc.
1252
darvid79ea26f72018-03-22 15:52:20 +11001253<a id="s2.17.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001254<a id="2173-cons"></a>
1255
1256<a id="decorators-cons"></a>
1257#### 2.17.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -05001258
1259Decorators can perform arbitrary operations on a function's arguments or return
1260values, resulting in surprising implicit behavior. Additionally, decorators
1261execute at import time. Failures in decorator code are pretty much impossible to
1262recover from.
1263
darvid79ea26f72018-03-22 15:52:20 +11001264<a id="s2.17.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001265<a id="2174-decision"></a>
1266
1267<a id="decorators-decision"></a>
1268#### 2.17.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -05001269
1270Use decorators judiciously when there is a clear advantage. Decorators should
1271follow the same import and naming guidelines as functions. Decorator pydoc
1272should clearly state that the function is a decorator. Write unit tests for
1273decorators.
1274
1275Avoid external dependencies in the decorator itself (e.g. don't rely on files,
1276sockets, database connections, etc.), since they might not be available when the
1277decorator runs (at import time, perhaps from `pydoc` or other tools). A
1278decorator that is called with valid parameters should (as much as possible) be
1279guaranteed to succeed in all cases.
1280
1281Decorators are a special case of "top level code" - see [main](#s3.17-main) for
1282more discussion.
1283
1284Never use `@staticmethod` unless forced to in order to integrate with an API
1285defined in an existing library. Write a module level function instead.
1286
1287Use `@classmethod` only when writing a named constructor or a class-specific
1288routine that modifies necessary global state such as a process-wide cache.
1289
1290<a id="s2.18-threading"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001291<a id="218-threading"></a>
1292
Google Python teamcfce3c32018-02-05 15:51:47 -05001293<a id="threading"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001294### 2.18 Threading
Google Python teamcfce3c32018-02-05 15:51:47 -05001295
1296Do not rely on the atomicity of built-in types.
1297
1298While Python's built-in data types such as dictionaries appear to have atomic
1299operations, there are corner cases where they aren't atomic (e.g. if `__hash__`
1300or `__eq__` are implemented as Python methods) and their atomicity should not be
1301relied upon. Neither should you rely on atomic variable assignment (since this
1302in turn depends on dictionaries).
1303
1304Use the Queue module's `Queue` data type as the preferred way to communicate
1305data between threads. Otherwise, use the threading module and its locking
1306primitives. Learn about the proper use of condition variables so you can use
1307`threading.Condition` instead of using lower-level locks.
1308
1309<a id="s2.19-power-features"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001310<a id="219-power-features"></a>
1311
Google Python teamcfce3c32018-02-05 15:51:47 -05001312<a id="power-features"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001313### 2.19 Power Features
Google Python teamcfce3c32018-02-05 15:51:47 -05001314
1315Avoid these features.
1316
darvid79ea26f72018-03-22 15:52:20 +11001317<a id="s2.19.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001318<a id="2191-definition"></a>
1319
1320<a id="power-features-definition"></a>
1321#### 2.19.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -05001322
1323Python is an extremely flexible language and gives you many fancy features such
1324as custom metaclasses, access to bytecode, on-the-fly compilation, dynamic
Google Python teamad22a752018-11-15 07:47:37 -08001325inheritance, object reparenting, import hacks, reflection (e.g. some uses of
1326`getattr()`), modification of system internals, etc.
Google Python teamcfce3c32018-02-05 15:51:47 -05001327
darvid79ea26f72018-03-22 15:52:20 +11001328<a id="s2.19.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001329<a id="2192-pros"></a>
1330
1331<a id="power-features-pros"></a>
1332#### 2.19.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -05001333
1334These are powerful language features. They can make your code more compact.
1335
darvid79ea26f72018-03-22 15:52:20 +11001336<a id="s2.19.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001337<a id="2193-cons"></a>
1338
1339<a id="power-features-cons"></a>
1340#### 2.19.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -05001341
1342It's very tempting to use these "cool" features when they're not absolutely
1343necessary. It's harder to read, understand, and debug code that's using unusual
1344features underneath. It doesn't seem that way at first (to the original author),
1345but when revisiting the code, it tends to be more difficult than code that is
1346longer but is straightforward.
1347
darvid79ea26f72018-03-22 15:52:20 +11001348<a id="s2.19.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001349<a id="2194-decision"></a>
1350
1351<a id="power-features-decision"></a>
1352#### 2.19.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -05001353
1354Avoid these features in your code.
1355
1356Standard library modules and classes that internally use these features are okay
Google Python teamad22a752018-11-15 07:47:37 -08001357to use (for example, `abc.ABCMeta`, `collections.namedtuple`, `dataclasses`,
1358and `enum`).
Google Python teamcfce3c32018-02-05 15:51:47 -05001359
1360<a id="s2.20-modern-python"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001361<a id="220-modern-python"></a>
1362
Google Python teamcfce3c32018-02-05 15:51:47 -05001363<a id="modern-python"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001364### 2.20 Modern Python: Python 3 and from \_\_future\_\_ imports
Google Python teamcfce3c32018-02-05 15:51:47 -05001365
Google Python teamad22a752018-11-15 07:47:37 -08001366Python 3 is here! While not every project is ready to
1367use it yet, all code should be written to be 3 compatible (and tested under
13683 when possible).
Google Python teamcfce3c32018-02-05 15:51:47 -05001369
darvid79ea26f72018-03-22 15:52:20 +11001370<a id="s2.20.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001371<a id="2201-definition"></a>
1372
1373<a id="modern-python-definition"></a>
1374#### 2.20.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -05001375
1376Python 3 is a significant change in the Python language. While existing code is
Google Python team6271f3f2018-12-05 14:40:50 -08001377often written with 2.7 in mind, there are some simple things to do to make code
Google Python teamcfce3c32018-02-05 15:51:47 -05001378more explicit about its intentions and thus better prepared for use under Python
13793 without modification.
1380
darvid79ea26f72018-03-22 15:52:20 +11001381<a id="s2.20.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001382<a id="2202-pros"></a>
1383
1384<a id="modern-python-pros"></a>
1385#### 2.20.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -05001386
1387Code written with Python 3 in mind is more explicit and easier to get running
1388under Python 3 once all of the dependencies of your project are ready.
1389
darvid79ea26f72018-03-22 15:52:20 +11001390<a id="s2.20.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001391<a id="2203-cons"></a>
1392
1393<a id="modern-python-cons"></a>
1394#### 2.20.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -05001395
Google Python teamad22a752018-11-15 07:47:37 -08001396Some people find the additional boilerplate to be ugly. It's unusual to add
1397imports to a module that doesn't actually require the features added by the
1398import.
Google Python teamcfce3c32018-02-05 15:51:47 -05001399
darvid79ea26f72018-03-22 15:52:20 +11001400<a id="s2.20.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001401<a id="2204-decision"></a>
1402
1403<a id="modern-python-decision"></a>
1404#### 2.20.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -05001405
1406##### from \_\_future\_\_ imports
1407
1408Use of `from __future__ import` statements is encouraged. All new code should
1409contain the following and existing code should be updated to be compatible when
1410possible:
1411
Google Python team5b06d2d2018-11-18 18:21:51 -08001412```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001413from __future__ import absolute_import
1414from __future__ import division
1415from __future__ import print_function
1416```
1417
1418If you are not already familiar with those, read up on each here: [absolute
1419imports](https://www.python.org/dev/peps/pep-0328/), [new `/` division
1420behavior](https://www.python.org/dev/peps/pep-0238/), and [the print
1421function](https://www.python.org/dev/peps/pep-3105/).
1422
Google Python team83a9e8d2019-10-10 00:40:18 -07001423
1424Please don't omit or remove these imports, even if they're not currently used in
1425the module, unless the code is Python 3 only. It is better to always have the
1426future imports in all files so that they are not forgotten during later edits
1427when someone starts using such a feature.
Google Python teamad22a752018-11-15 07:47:37 -08001428
Google Python teamcfce3c32018-02-05 15:51:47 -05001429There are other `from __future__` import statements. Use them as you see fit. We
1430do not include `unicode_literals` in our recommendations as it is not a clear
1431win due to implicit default codec conversion consequences it introduces in many
1432places within Python 2.7. Most code is better off with explicit use of `b''` and
1433`u''` bytes and unicode string literals as necessary.
1434
Google Python team83a9e8d2019-10-10 00:40:18 -07001435##### The six, future, or past libraries
Google Python teamcfce3c32018-02-05 15:51:47 -05001436
1437When your project needs to actively support use under both Python 2 and 3, use
Google Python team83a9e8d2019-10-10 00:40:18 -07001438the [six](https://pypi.org/project/six/),
1439[future](https://pypi.org/project/future/), and
1440[past](https://pypi.org/project/past/) libraries as you see fit. They exist to
1441make your code cleaner and life easier.
Google Python teamcfce3c32018-02-05 15:51:47 -05001442
1443<a name="s2.21-typed-code"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001444<a name="221-type-annotated-code"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05001445<a name="typed-code"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001446
1447<a id="typed-code"></a>
1448### 2.21 Type Annotated Code
Google Python teamcfce3c32018-02-05 15:51:47 -05001449
1450You can annotate Python 3 code with type hints according to
1451[PEP-484](https://www.python.org/dev/peps/pep-0484/), and type-check the code at
1452build time with a type checking tool like
1453[pytype](https://github.com/google/pytype).
1454
1455
1456Type annotations can be in the source or in a [stub pyi
1457file](https://www.python.org/dev/peps/pep-0484/#stub-files). Whenever possible,
1458annotations should be in the source. Use pyi files for third-party or extension
1459modules.
1460
1461
darvid79ea26f72018-03-22 15:52:20 +11001462<a id="s2.21.1-definition"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001463<a id="2211-definition"></a>
1464
1465<a id="typed-code-definition"></a>
1466#### 2.21.1 Definition
Google Python teamcfce3c32018-02-05 15:51:47 -05001467
1468Type annotations (or "type hints") are for function or method arguments and
1469return values:
1470
Google Python team5b06d2d2018-11-18 18:21:51 -08001471```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001472def func(a: int) -> List[int]:
1473```
1474
1475You can also declare the type of a variable using a special comment:
1476
Google Python team5b06d2d2018-11-18 18:21:51 -08001477```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001478a = SomeFunc() # type: SomeType
1479```
1480
darvid79ea26f72018-03-22 15:52:20 +11001481<a id="s2.21.2-pros"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001482<a id="2212-pros"></a>
1483
1484<a id="typed-code-pros"></a>
1485#### 2.21.2 Pros
Google Python teamcfce3c32018-02-05 15:51:47 -05001486
1487Type annotations improve the readability and maintainability of your code. The
1488type checker will convert many runtime errors to build-time errors, and reduce
1489your ability to use [Power Features](#power-features).
1490
darvid79ea26f72018-03-22 15:52:20 +11001491<a id="s2.21.3-cons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001492<a id="2213-cons"></a>
1493
1494<a id="typed-code-cons"></a>
1495#### 2.21.3 Cons
Google Python teamcfce3c32018-02-05 15:51:47 -05001496
1497You 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)
1498may reduce your ability to use [Power Features](#power-features).
1499
darvid79ea26f72018-03-22 15:52:20 +11001500<a id="s2.21.4-decision"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001501<a id="2214-decision"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05001502
Google Python team83a9e8d2019-10-10 00:40:18 -07001503<a id="typed-code-decision"></a>
1504#### 2.21.4 Decision
Google Python teamcfce3c32018-02-05 15:51:47 -05001505
Google Python team83a9e8d2019-10-10 00:40:18 -07001506You are strongly encouraged to enable Python type analysis when updating code.
1507When adding or modifying public APIs, include type annotations and enable
1508checking via pytype in the build system. As static analysis is relatively new to
1509Python, we acknowledge that undesired side-effects (such as
1510wrongly
1511inferred types) may prevent adoption by some projects. In those situations,
1512authors are encouraged to add a comment with a TODO or link to a bug describing
1513the issue(s) currently preventing type annotation adoption in the BUILD file or
1514in the code itself as appropriate.
Google Python teamcfce3c32018-02-05 15:51:47 -05001515
1516<a id="s3-python-style-rules"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001517<a id="3-python-style-rules"></a>
1518
Google Python teamcfce3c32018-02-05 15:51:47 -05001519<a id="python-style-rules"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001520## 3 Python Style Rules
Google Python teamcfce3c32018-02-05 15:51:47 -05001521
1522<a id="s3.1-semicolons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001523<a id="31-semicolons"></a>
1524
Google Python teamcfce3c32018-02-05 15:51:47 -05001525<a id="semicolons"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001526### 3.1 Semicolons
Google Python teamcfce3c32018-02-05 15:51:47 -05001527
Google Python team6271f3f2018-12-05 14:40:50 -08001528Do not terminate your lines with semicolons, and do not use semicolons to put
Google Python teamcfce3c32018-02-05 15:51:47 -05001529two statements on the same line.
1530
1531<a id="s3.2-line-length"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001532<a id="32-line-length"></a>
1533
Google Python teamcfce3c32018-02-05 15:51:47 -05001534<a id="line-length"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001535### 3.2 Line length
Google Python teamcfce3c32018-02-05 15:51:47 -05001536
1537Maximum line length is *80 characters*.
1538
Google Python team83a9e8d2019-10-10 00:40:18 -07001539Explicit exceptions to the 80 character limit:
Google Python teamcfce3c32018-02-05 15:51:47 -05001540
1541- Long import statements.
1542- URLs, pathnames, or long flags in comments.
1543- Long string module level constants not containing whitespace that would be
1544 inconvenient to split across lines such as URLs or pathnames.
1545- Pylint disable comments. (e.g.: `# pylint: disable=invalid-name`)
1546
1547Do not use backslash line continuation except for `with` statements requiring
1548three or more context managers.
1549
1550Make use of Python's [implicit line joining inside parentheses, brackets and
1551braces](http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining).
1552If necessary, you can add an extra pair of parentheses around an expression.
1553
Google Python team5b06d2d2018-11-18 18:21:51 -08001554```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001555Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
1556 emphasis=None, highlight=0)
1557
1558 if (width == 0 and height == 0 and
1559 color == 'red' and emphasis == 'strong'):
1560```
1561
1562When a literal string won't fit on a single line, use parentheses for implicit
1563line joining.
1564
Google Python team5b06d2d2018-11-18 18:21:51 -08001565```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001566x = ('This will build a very long long '
1567 'long long long long long long string')
1568```
1569
1570Within comments, put long URLs on their own line if necessary.
1571
Google Python team5b06d2d2018-11-18 18:21:51 -08001572```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001573Yes: # See details at
1574 # http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
1575```
1576
Google Python team5b06d2d2018-11-18 18:21:51 -08001577```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001578No: # See details at
1579 # http://www.example.com/us/developer/documentation/api/content/\
1580 # v2.0/csv_file_name_extension_full_specification.html
1581```
1582
1583It is permissible to use backslash continuation when defining a `with` statement
1584whose expressions span three or more lines. For two lines of expressions, use a
1585nested `with` statement:
1586
Google Python team5b06d2d2018-11-18 18:21:51 -08001587```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001588Yes: with very_long_first_expression_function() as spam, \
1589 very_long_second_expression_function() as beans, \
1590 third_thing() as eggs:
1591 place_order(eggs, beans, spam, beans)
1592```
1593
Google Python team5b06d2d2018-11-18 18:21:51 -08001594```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001595No: with VeryLongFirstExpressionFunction() as spam, \
1596 VeryLongSecondExpressionFunction() as beans:
1597 PlaceOrder(eggs, beans, spam, beans)
1598```
1599
Google Python team5b06d2d2018-11-18 18:21:51 -08001600```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001601Yes: with very_long_first_expression_function() as spam:
1602 with very_long_second_expression_function() as beans:
1603 place_order(beans, spam)
1604```
1605
1606Make note of the indentation of the elements in the line continuation examples
1607above; see the [indentation](#s3.4-indentation) section for explanation.
1608
Google Python team83a9e8d2019-10-10 00:40:18 -07001609In all other cases where a line exceeds 80 characters, and the
1610[yapf](https://github.com/google/yapf/)
1611auto-formatter does not help bring the line below the limit, the line is allowed
1612to exceed this maximum.
1613
Google Python teamcfce3c32018-02-05 15:51:47 -05001614<a id="s3.3-parentheses"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001615<a id="33-parentheses"></a>
1616
Google Python teamcfce3c32018-02-05 15:51:47 -05001617<a id="parentheses"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001618### 3.3 Parentheses
Google Python teamcfce3c32018-02-05 15:51:47 -05001619
1620Use parentheses sparingly.
1621
1622It is fine, though not required, to use parentheses around tuples. Do not use
1623them in return statements or conditional statements unless using parentheses for
1624implied line continuation or to indicate a tuple.
1625
Google Python team5b06d2d2018-11-18 18:21:51 -08001626```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001627Yes: if foo:
1628 bar()
1629 while x:
1630 x = bar()
1631 if x and y:
1632 bar()
1633 if not x:
1634 bar()
1635 # For a 1 item tuple the ()s are more visually obvious than the comma.
1636 onesie = (foo,)
1637 return foo
1638 return spam, beans
1639 return (spam, beans)
1640 for (x, y) in dict.items(): ...
1641```
1642
Google Python team5b06d2d2018-11-18 18:21:51 -08001643```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001644No: if (x):
1645 bar()
1646 if not(x):
1647 bar()
1648 return (foo)
1649```
1650
Google Python teamcfce3c32018-02-05 15:51:47 -05001651<a id="s3.4-indentation"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001652<a id="34-indentation"></a>
1653
Google Python teamcfce3c32018-02-05 15:51:47 -05001654<a id="indentation"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001655### 3.4 Indentation
Google Python teamcfce3c32018-02-05 15:51:47 -05001656
1657Indent your code blocks with *4 spaces*.
1658
1659Never use tabs or mix tabs and spaces. In cases of implied line continuation,
1660you should align wrapped elements either vertically, as per the examples in the
1661[line length](#s3.2-line-length) section; or using a hanging indent of 4 spaces,
1662in which case there should be nothing after the open parenthesis or bracket on
1663the first line.
1664
Google Python team5b06d2d2018-11-18 18:21:51 -08001665```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001666Yes: # Aligned with opening delimiter
1667 foo = long_function_name(var_one, var_two,
1668 var_three, var_four)
1669 meal = (spam,
1670 beans)
1671
1672 # Aligned with opening delimiter in a dictionary
1673 foo = {
1674 long_dictionary_key: value1 +
1675 value2,
1676 ...
1677 }
1678
1679 # 4-space hanging indent; nothing on first line
1680 foo = long_function_name(
1681 var_one, var_two, var_three,
1682 var_four)
1683 meal = (
1684 spam,
1685 beans)
1686
1687 # 4-space hanging indent in a dictionary
1688 foo = {
1689 long_dictionary_key:
1690 long_dictionary_value,
1691 ...
1692 }
1693```
1694
Google Python team5b06d2d2018-11-18 18:21:51 -08001695```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001696No: # Stuff on first line forbidden
1697 foo = long_function_name(var_one, var_two,
1698 var_three, var_four)
1699 meal = (spam,
1700 beans)
1701
1702 # 2-space hanging indent forbidden
1703 foo = long_function_name(
1704 var_one, var_two, var_three,
1705 var_four)
1706
1707 # No hanging indent in a dictionary
1708 foo = {
1709 long_dictionary_key:
1710 long_dictionary_value,
1711 ...
1712 }
1713```
1714
Google Python teamad22a752018-11-15 07:47:37 -08001715<a id="s3.4.1-trailing_comma"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001716<a id="341-trailing_comma"></a>
Google Python teamad22a752018-11-15 07:47:37 -08001717<a id="trailing_comma"></a>
1718
Google Python team83a9e8d2019-10-10 00:40:18 -07001719<a id="trailing-comma"></a>
1720### 3.4.1 Trailing commas in sequences of items?
Google Python teamad22a752018-11-15 07:47:37 -08001721
1722Trailing commas in sequences of items are recommended only when the closing
1723container token `]`, `)`, or `}` does not appear on the same line as the final
1724element. The presence of a trailing comma is also used as a hint to our Python
1725code auto-formatter [YAPF](https://pypi.org/project/yapf/) to direct it to auto-format the container
1726of items to one item per line when the `,` after the final element is present.
1727
Google Python team5b06d2d2018-11-18 18:21:51 -08001728```python
Google Python teamad22a752018-11-15 07:47:37 -08001729Yes: golomb3 = [0, 1, 3]
1730Yes: golomb4 = [
1731 0,
1732 1,
1733 4,
1734 6,
1735 ]
1736```
1737
Google Python team5b06d2d2018-11-18 18:21:51 -08001738```python
Google Python teamad22a752018-11-15 07:47:37 -08001739No: golomb4 = [
1740 0,
1741 1,
1742 4,
1743 6
1744 ]
1745```
1746
Google Python teamcfce3c32018-02-05 15:51:47 -05001747<a id="s3.5-blank-lines"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001748<a id="35-blank-lines"></a>
1749
Google Python teamcfce3c32018-02-05 15:51:47 -05001750<a id="blank-lines"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001751### 3.5 Blank Lines
Google Python teamcfce3c32018-02-05 15:51:47 -05001752
Google Python teamcfce3c32018-02-05 15:51:47 -05001753Two blank lines between top-level definitions, be they function or class
1754definitions. One blank line between method definitions and between the `class`
Google Python teamfdc20e82018-11-28 10:15:08 -08001755line and the first method. No blank line following a `def` line. Use single
1756blank lines as you judge appropriate within functions or methods.
Google Python teamcfce3c32018-02-05 15:51:47 -05001757
1758<a id="s3.6-whitespace"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001759<a id="36-whitespace"></a>
1760
Google Python teamcfce3c32018-02-05 15:51:47 -05001761<a id="whitespace"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001762### 3.6 Whitespace
Google Python teamcfce3c32018-02-05 15:51:47 -05001763
1764Follow standard typographic rules for the use of spaces around punctuation.
1765
1766No whitespace inside parentheses, brackets or braces.
1767
Google Python team5b06d2d2018-11-18 18:21:51 -08001768```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001769Yes: spam(ham[1], {eggs: 2}, [])
1770```
1771
Google Python team5b06d2d2018-11-18 18:21:51 -08001772```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001773No: spam( ham[ 1 ], { eggs: 2 }, [ ] )
1774```
1775
1776No whitespace before a comma, semicolon, or colon. Do use whitespace after a
Google Python team6271f3f2018-12-05 14:40:50 -08001777comma, semicolon, or colon, except at the end of the line.
Google Python teamcfce3c32018-02-05 15:51:47 -05001778
Google Python team5b06d2d2018-11-18 18:21:51 -08001779```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001780Yes: if x == 4:
1781 print(x, y)
1782 x, y = y, x
1783```
1784
Google Python team5b06d2d2018-11-18 18:21:51 -08001785```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001786No: if x == 4 :
1787 print(x , y)
1788 x , y = y , x
1789```
1790
1791No whitespace before the open paren/bracket that starts an argument list,
1792indexing or slicing.
1793
Google Python team5b06d2d2018-11-18 18:21:51 -08001794```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001795Yes: spam(1)
1796```
1797
Google Python team5b06d2d2018-11-18 18:21:51 -08001798```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001799No: spam (1)
1800```
1801
1802
Google Python team5b06d2d2018-11-18 18:21:51 -08001803```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001804Yes: dict['key'] = list[index]
1805```
1806
Google Python team5b06d2d2018-11-18 18:21:51 -08001807```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001808No: dict ['key'] = list [index]
1809```
1810
Google Python team83a9e8d2019-10-10 00:40:18 -07001811No trailing whitespace.
1812
Google Python teamcfce3c32018-02-05 15:51:47 -05001813Surround binary operators with a single space on either side for assignment
1814(`=`), comparisons (`==, <, >, !=, <>, <=, >=, in, not in, is, is not`), and
1815Booleans (`and, or, not`). Use your better judgment for the insertion of spaces
Google Python teamad22a752018-11-15 07:47:37 -08001816around arithmetic operators (`+`, `-`, `*`, `/`, `//`, `%`, `**`, `@`).
Google Python teamcfce3c32018-02-05 15:51:47 -05001817
Google Python team5b06d2d2018-11-18 18:21:51 -08001818```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001819Yes: x == 1
1820```
1821
Google Python team5b06d2d2018-11-18 18:21:51 -08001822```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001823No: x<1
1824```
1825
Google Python team6271f3f2018-12-05 14:40:50 -08001826Never use spaces around `=` when passing keyword arguments or defining a default
1827parameter value, with one exception: [when a type annotation is
1828present](#typing-default-values), _do_ use spaces around the `=` for the default
1829parameter value.
Google Python teamcfce3c32018-02-05 15:51:47 -05001830
Google Python team5b06d2d2018-11-18 18:21:51 -08001831```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001832Yes: def complex(real, imag=0.0): return Magic(r=real, i=imag)
1833Yes: def complex(real, imag: float = 0.0): return Magic(r=real, i=imag)
1834```
1835
Google Python team5b06d2d2018-11-18 18:21:51 -08001836```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001837No: def complex(real, imag = 0.0): return Magic(r = real, i = imag)
1838No: def complex(real, imag: float=0.0): return Magic(r = real, i = imag)
1839```
1840
1841Don't use spaces to vertically align tokens on consecutive lines, since it
1842becomes a maintenance burden (applies to `:`, `#`, `=`, etc.):
1843
Google Python team5b06d2d2018-11-18 18:21:51 -08001844```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001845Yes:
1846 foo = 1000 # comment
1847 long_name = 2 # comment that should not be aligned
1848
1849 dictionary = {
1850 'foo': 1,
1851 'long_name': 2,
1852 }
1853```
1854
Google Python team5b06d2d2018-11-18 18:21:51 -08001855```python
Google Python teamcfce3c32018-02-05 15:51:47 -05001856No:
1857 foo = 1000 # comment
1858 long_name = 2 # comment that should not be aligned
1859
1860 dictionary = {
1861 'foo' : 1,
1862 'long_name': 2,
1863 }
1864```
1865
1866
1867<a id="Python_Interpreter"></a>
1868<a id="s3.7-shebang-line"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001869<a id="37-shebang-line"></a>
1870
Google Python teamcfce3c32018-02-05 15:51:47 -05001871<a id="shebang-line"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001872### 3.7 Shebang Line
Google Python teamcfce3c32018-02-05 15:51:47 -05001873
1874Most `.py` files do not need to start with a `#!` line. Start the main file of a
1875program with
1876`#!/usr/bin/python` with an optional single digit `2` or `3` suffix per
1877[PEP-394](https://www.google.com/url?sa=D&q=http://www.python.org/dev/peps/pep-0394/).
1878
1879This line is used by the kernel to find the Python interpreter, but is ignored
1880by Python when importing modules. It is only necessary on a file that will be
1881executed directly.
1882
1883<a id="s3.8-comments"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001884<a id="38-comments-and-docstrings"></a>
1885
1886<a id="documentation"></a>
1887### 3.8 Comments and Docstrings
Google Python teamcfce3c32018-02-05 15:51:47 -05001888
1889Be sure to use the right style for module, function, method docstrings and
Google Python teamad22a752018-11-15 07:47:37 -08001890inline comments.
Google Python teamcfce3c32018-02-05 15:51:47 -05001891
1892<a id="s3.8.1-comments-in-doc-strings"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001893<a id="381-docstrings"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05001894<a id="comments-in-doc-strings"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001895
1896<a id="docstrings"></a>
1897#### 3.8.1 Docstrings
Google Python teamcfce3c32018-02-05 15:51:47 -05001898
Google Python team6271f3f2018-12-05 14:40:50 -08001899Python uses _docstrings_ to document code. A docstring is a string that is the
Google Python teamcfce3c32018-02-05 15:51:47 -05001900first statement in a package, module, class or function. These strings can be
1901extracted automatically through the `__doc__` member of the object and are used
1902by `pydoc`.
1903(Try running `pydoc` on your module to see how it looks.) Always use the three
1904double-quote `"""` format for docstrings (per [PEP
1905257](https://www.google.com/url?sa=D&q=http://www.python.org/dev/peps/pep-0257/)).
1906A docstring should be organized as a summary line (one physical line) terminated
1907by a period, question mark, or exclamation point, followed by a blank line,
1908followed by the rest of the docstring starting at the same cursor position as
1909the first quote of the first line. There are more formatting guidelines for
1910docstrings below.
1911
1912<a id="s3.8.2-comments-in-modules"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001913<a id="382-modules"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05001914<a id="comments-in-modules"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05001915
Google Python team83a9e8d2019-10-10 00:40:18 -07001916<a id="module-docs"></a>
1917#### 3.8.2 Modules
1918
1919Every file should contain license boilerplate.
1920Choose the appropriate boilerplate for the license used by the project (for
1921example, Apache 2.0, BSD, LGPL, GPL)
1922
1923Files should start with a docstring describing the contents and usage of the
1924module.
1925```python
1926"""A one line summary of the module or program, terminated by a period.
1927
1928Leave one blank line. The rest of this docstring should contain an
1929overall description of the module or program. Optionally, it may also
1930contain a brief description of exported classes and functions and/or usage
1931examples.
1932
1933 Typical usage example:
1934
1935 foo = ClassFoo()
1936 bar = foo.FunctionBar()
1937"""
1938```
1939
Google Python teamcfce3c32018-02-05 15:51:47 -05001940
1941<a id="s3.8.3-functions-and-methods"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001942<a id="383-functions-and-methods"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05001943<a id="functions-and-methods"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07001944
1945<a id="function-docs"></a>
1946#### 3.8.3 Functions and Methods
Google Python teamcfce3c32018-02-05 15:51:47 -05001947
Google Python team6271f3f2018-12-05 14:40:50 -08001948In this section, "function" means a method, function, or generator.
Google Python teamcfce3c32018-02-05 15:51:47 -05001949
1950A function must have a docstring, unless it meets all of the following criteria:
1951
1952- not externally visible
1953- very short
1954- obvious
1955
1956A docstring should give enough information to write a call to the function
Google Python team83a9e8d2019-10-10 00:40:18 -07001957without reading the function's code. The docstring should be descriptive-style
1958(`"""Fetches rows from a Bigtable."""`) rather than imperative-style (`"""Fetch
1959rows from a Bigtable."""`), except for `@property` data descriptors, which
1960should use the <a href="#384-classes">same style as attributes</a>. A docstring
1961should describe the function's calling syntax and its semantics, not its
1962implementation. For tricky code, comments alongside the code are more
1963appropriate than using docstrings.
Google Python teamcfce3c32018-02-05 15:51:47 -05001964
1965A method that overrides a method from a base class may have a simple docstring
Google Python team6271f3f2018-12-05 14:40:50 -08001966sending the reader to its overridden method's docstring, such as `"""See base
1967class."""`. The rationale is that there is no need to repeat in many places
1968documentation that is already present in the base method's docstring. However,
1969if the overriding method's behavior is substantially different from the
1970overridden method, or details need to be provided (e.g., documenting additional
1971side effects), a docstring with at least those differences is required on the
1972overriding method.
Google Python teamcfce3c32018-02-05 15:51:47 -05001973
1974Certain aspects of a function should be documented in special sections, listed
Google Python team83a9e8d2019-10-10 00:40:18 -07001975below. Each section begins with a heading line, which ends with a colon. All
1976sections other than the heading should maintain a hanging indent of two or four
1977spaces (be consistent within a file). These sections can be omitted in cases
1978where the function's name and signature are informative enough that it can be
1979aptly described using a one-line docstring.
Google Python teamcfce3c32018-02-05 15:51:47 -05001980
Google Python teamfdc20e82018-11-28 10:15:08 -08001981<a id="doc-function-args"></a>
1982[*Args:*](#doc-function-args)
1983: List each parameter by name. A description should follow the name, and be
Google Python team83a9e8d2019-10-10 00:40:18 -07001984 separated by a colon and a space. If the description is too long to fit on a
1985 single 80-character line, use a hanging indent of 2 or 4 spaces (be
1986 consistent with the rest of the file).
1987
1988 The description should include required type(s) if the code does not contain
1989 a corresponding type annotation. If a function accepts `*foo` (variable
1990 length argument lists) and/or `**bar` (arbitrary keyword arguments), they
1991 should be listed as `*foo` and `**bar`.
Google Python teamcfce3c32018-02-05 15:51:47 -05001992
Google Python teamfdc20e82018-11-28 10:15:08 -08001993<a id="doc-function-returns"></a>
1994[*Returns:* (or *Yields:* for generators)](#doc-function-returns)
Google Python teamad22a752018-11-15 07:47:37 -08001995: Describe the type and semantics of the return value. If the function only
Google Python team83a9e8d2019-10-10 00:40:18 -07001996 returns None, this section is not required. It may also be omitted if the
1997 docstring starts with Returns or Yields (e.g. `"""Returns row from Bigtable
1998 as a tuple of strings."""`) and the opening sentence is sufficient to
1999 describe return value.
Google Python teamcfce3c32018-02-05 15:51:47 -05002000
Google Python teamfdc20e82018-11-28 10:15:08 -08002001<a id="doc-function-raises"></a>
2002[*Raises:*](#doc-function-raises)
Google Python team83a9e8d2019-10-10 00:40:18 -07002003: List all exceptions that are relevant to the interface. You should not
2004 document exceptions that get raised if the API specified in the docstring is
2005 violated (because this would paradoxically make behavior under violation of
2006 the API part of the API).
Google Python teamcfce3c32018-02-05 15:51:47 -05002007
Google Python team5b06d2d2018-11-18 18:21:51 -08002008```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002009def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
2010 """Fetches rows from a Bigtable.
2011
2012 Retrieves rows pertaining to the given keys from the Table instance
2013 represented by big_table. Silly things may happen if
2014 other_silly_variable is not None.
2015
2016 Args:
2017 big_table: An open Bigtable Table instance.
2018 keys: A sequence of strings representing the key of each table row
2019 to fetch.
2020 other_silly_variable: Another optional variable, that has a much
2021 longer name than the other args, and which does nothing.
2022
2023 Returns:
2024 A dict mapping keys to the corresponding table row data
2025 fetched. Each row is represented as a tuple of strings. For
2026 example:
2027
2028 {'Serak': ('Rigel VII', 'Preparer'),
2029 'Zim': ('Irk', 'Invader'),
2030 'Lrrr': ('Omicron Persei 8', 'Emperor')}
2031
2032 If a key from the keys argument is missing from the dictionary,
2033 then that row was not found in the table.
2034
2035 Raises:
2036 IOError: An error occurred accessing the bigtable.Table object.
2037 """
2038```
2039
2040<a id="s3.8.4-comments-in-classes"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002041<a id="384-classes"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05002042<a id="comments-in-classes"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002043
2044<a id="class-docs"></a>
2045#### 3.8.4 Classes
Google Python teamcfce3c32018-02-05 15:51:47 -05002046
2047Classes should have a docstring below the class definition describing the class.
2048If your class has public attributes, they should be documented here in an
Google Python teamad22a752018-11-15 07:47:37 -08002049`Attributes` section and follow the same formatting as a
2050[function's `Args`](#doc-function-args) section.
Google Python teamcfce3c32018-02-05 15:51:47 -05002051
Google Python team5b06d2d2018-11-18 18:21:51 -08002052```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002053class SampleClass(object):
2054 """Summary of class here.
2055
2056 Longer class information....
2057 Longer class information....
2058
2059 Attributes:
2060 likes_spam: A boolean indicating if we like SPAM or not.
2061 eggs: An integer count of the eggs we have laid.
2062 """
2063
2064 def __init__(self, likes_spam=False):
2065 """Inits SampleClass with blah."""
2066 self.likes_spam = likes_spam
2067 self.eggs = 0
2068
2069 def public_method(self):
2070 """Performs operation blah."""
2071```
2072
2073<a id="comments-in-block-and-inline"></a>
2074<a id="s3.8.5-comments-in-block-and-inline"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002075<a id="385-block-and-inline-comments"></a>
2076
2077<a id="comments"></a>
2078#### 3.8.5 Block and Inline Comments
Google Python teamcfce3c32018-02-05 15:51:47 -05002079
2080The final place to have comments is in tricky parts of the code. If you're going
2081to have to explain it at the next [code
2082review](http://en.wikipedia.org/wiki/Code_review), you should comment it
2083now. Complicated operations get a few lines of comments before the operations
2084commence. Non-obvious ones get comments at the end of the line.
2085
Google Python team5b06d2d2018-11-18 18:21:51 -08002086```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002087# We use a weighted dictionary search to find out where i is in
2088# the array. We extrapolate position based on the largest num
2089# in the array and the array size and then do binary search to
2090# get the exact number.
2091
2092if i & (i-1) == 0: # True if i is 0 or a power of 2.
2093```
2094
Google Python team83a9e8d2019-10-10 00:40:18 -07002095To improve legibility, these comments should start at least 2 spaces away from
2096the code with the comment character `#`, followed by at least one space before
2097the text of the comment itself.
Google Python teamcfce3c32018-02-05 15:51:47 -05002098
2099On the other hand, never describe the code. Assume the person reading the code
2100knows Python (though not what you're trying to do) better than you do.
2101
Google Python team5b06d2d2018-11-18 18:21:51 -08002102```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002103# BAD COMMENT: Now go through the b array and make sure whenever i occurs
2104# the next element is i+1
2105```
2106
2107<!-- The next section is copied from the C++ style guide. -->
Google Python team83a9e8d2019-10-10 00:40:18 -07002108
Google Python teamcfce3c32018-02-05 15:51:47 -05002109<a id="s3.8.6-punctuation-spelling-and-grammar"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002110<a id="386-punctuation-spelling-and-grammar"></a>
2111<a id="spelling"></a>
2112<a id="punctuation"></a>
2113<a id="grammar"></a>
2114
2115<a id="punctuation-spelling-grammar"></a>
2116#### 3.8.6 Punctuation, Spelling and Grammar
Google Python teamcfce3c32018-02-05 15:51:47 -05002117
2118Pay attention to punctuation, spelling, and grammar; it is easier to read
2119well-written comments than badly written ones.
2120
2121Comments should be as readable as narrative text, with proper capitalization and
2122punctuation. In many cases, complete sentences are more readable than sentence
2123fragments. Shorter comments, such as comments at the end of a line of code, can
2124sometimes be less formal, but you should be consistent with your style.
2125
2126Although it can be frustrating to have a code reviewer point out that you are
2127using a comma when you should be using a semicolon, it is very important that
2128source code maintain a high level of clarity and readability. Proper
2129punctuation, spelling, and grammar help with that goal.
2130
2131<a id="s3.9-classes"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002132<a id="39-classes"></a>
2133
Google Python teamcfce3c32018-02-05 15:51:47 -05002134<a id="classes"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002135### 3.9 Classes
Google Python teamcfce3c32018-02-05 15:51:47 -05002136
2137If a class inherits from no other base classes, explicitly inherit from
2138`object`. This also applies to nested classes.
2139
Google Python team5b06d2d2018-11-18 18:21:51 -08002140```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002141Yes: class SampleClass(object):
2142 pass
2143
2144
2145 class OuterClass(object):
2146
2147 class InnerClass(object):
2148 pass
2149
2150
2151 class ChildClass(ParentClass):
2152 """Explicitly inherits from another class already."""
2153
2154```
2155
Google Python team5b06d2d2018-11-18 18:21:51 -08002156```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002157No: class SampleClass:
2158 pass
2159
2160
2161 class OuterClass:
2162
2163 class InnerClass:
2164 pass
2165```
2166
Google Python team6271f3f2018-12-05 14:40:50 -08002167Inheriting from `object` is needed to make properties work properly in Python 2
2168and can protect your code from potential incompatibility with Python 3. It also
2169defines special methods that implement the default semantics of objects
Google Python teamcfce3c32018-02-05 15:51:47 -05002170including `__new__`, `__init__`, `__delattr__`, `__getattribute__`,
2171`__setattr__`, `__hash__`, `__repr__`, and `__str__`.
2172
2173<a id="s3.10-strings"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002174<a id="310-strings"></a>
2175
Google Python teamcfce3c32018-02-05 15:51:47 -05002176<a id="strings"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002177### 3.10 Strings
Google Python teamcfce3c32018-02-05 15:51:47 -05002178
2179Use the `format` method or the `%` operator for formatting strings, even when
Google Python team83a9e8d2019-10-10 00:40:18 -07002180the parameters are all strings. Use your best judgment to decide between `+` and
2181`%` (or `format`) though.
Google Python teamcfce3c32018-02-05 15:51:47 -05002182
Google Python team5b06d2d2018-11-18 18:21:51 -08002183```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002184Yes: x = a + b
2185 x = '%s, %s!' % (imperative, expletive)
2186 x = '{}, {}'.format(first, second)
2187 x = 'name: %s; score: %d' % (name, n)
2188 x = 'name: {}; score: {}'.format(name, n)
2189 x = f'name: {name}; score: {n}' # Python 3.6+
2190```
2191
Google Python team5b06d2d2018-11-18 18:21:51 -08002192```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002193No: x = '%s%s' % (a, b) # use + in this case
2194 x = '{}{}'.format(a, b) # use + in this case
2195 x = first + ', ' + second
2196 x = 'name: ' + name + '; score: ' + str(n)
2197```
2198
2199Avoid using the `+` and `+=` operators to accumulate a string within a loop.
2200Since strings are immutable, this creates unnecessary temporary objects and
2201results in quadratic rather than linear running time. Instead, add each
2202substring to a list and `''.join` the list after the loop terminates (or, write
2203each substring to a `io.BytesIO` buffer).
2204
Google Python team5b06d2d2018-11-18 18:21:51 -08002205```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002206Yes: items = ['<table>']
2207 for last_name, first_name in employee_list:
2208 items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
2209 items.append('</table>')
2210 employee_table = ''.join(items)
2211```
2212
Google Python team5b06d2d2018-11-18 18:21:51 -08002213```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002214No: employee_table = '<table>'
2215 for last_name, first_name in employee_list:
2216 employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
2217 employee_table += '</table>'
2218```
2219
2220Be consistent with your choice of string quote character within a file. Pick `'`
2221or `"` and stick with it. It is okay to use the other quote character on a
Google Python team83a9e8d2019-10-10 00:40:18 -07002222string to avoid the need to `\\ ` escape within the string.
Google Python teamcfce3c32018-02-05 15:51:47 -05002223
Google Python team5b06d2d2018-11-18 18:21:51 -08002224```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002225Yes:
2226 Python('Why are you hiding your eyes?')
2227 Gollum("I'm scared of lint errors.")
2228 Narrator('"Good!" thought a happy Python reviewer.')
2229```
2230
Google Python team5b06d2d2018-11-18 18:21:51 -08002231```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002232No:
2233 Python("Why are you hiding your eyes?")
2234 Gollum('The lint. It burns. It burns us.')
2235 Gollum("Always the great lint. Watching. Watching.")
2236```
2237
2238Prefer `"""` for multi-line strings rather than `'''`. Projects may choose to
2239use `'''` for all non-docstring multi-line strings if and only if they also use
Google Python team83a9e8d2019-10-10 00:40:18 -07002240`'` for regular strings. Docstrings must use `"""` regardless.
Google Python teamcfce3c32018-02-05 15:51:47 -05002241
Google Python team83a9e8d2019-10-10 00:40:18 -07002242Multi-line strings do not flow with the indentation of the rest of the program.
2243If you need to avoid embedding extra space in the string, use either
2244concatenated single-line strings or a multi-line string with
2245[`textwrap.dedent()`](https://docs.python.org/3/library/textwrap.html#textwrap.dedent)
2246to remove the initial space on each line:
Google Python teamcfce3c32018-02-05 15:51:47 -05002247
Google Python team5b06d2d2018-11-18 18:21:51 -08002248```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002249 No:
Google Python team83a9e8d2019-10-10 00:40:18 -07002250 long_string = """This is pretty ugly.
Google Python teamcfce3c32018-02-05 15:51:47 -05002251Don't do this.
Google Python team83a9e8d2019-10-10 00:40:18 -07002252"""
2253```
2254
2255```python
2256 Yes:
2257 long_string = """This is fine if your use case can accept
2258 extraneous leading spaces."""
2259```
2260
2261```python
2262 Yes:
2263 long_string = ("And this is fine if you can not accept\n" +
2264 "extraneous leading spaces.")
2265```
2266
2267```python
2268 Yes:
2269 long_string = ("And this too is fine if you can not accept\n"
2270 "extraneous leading spaces.")
2271```
2272
2273```python
2274 Yes:
2275 import textwrap
2276
2277 long_string = textwrap.dedent("""\
2278 This is also fine, because textwrap.dedent()
2279 will collapse common leading spaces in each line.""")
Google Python teamcfce3c32018-02-05 15:51:47 -05002280```
2281
2282<a id="s3.11-files-and-sockets"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002283<a id="311-files-and-sockets"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05002284<a id="files-and-sockets"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002285
2286<a id="files"></a>
2287### 3.11 Files and Sockets
Google Python teamcfce3c32018-02-05 15:51:47 -05002288
2289Explicitly close files and sockets when done with them.
2290
2291Leaving files, sockets or other file-like objects open unnecessarily has many
Google Python team6271f3f2018-12-05 14:40:50 -08002292downsides:
Google Python teamcfce3c32018-02-05 15:51:47 -05002293
2294- They may consume limited system resources, such as file descriptors. Code
2295 that deals with many such objects may exhaust those resources unnecessarily
2296 if they're not returned to the system promptly after use.
Google Python team6271f3f2018-12-05 14:40:50 -08002297- Holding files open may prevent other actions such as moving or deleting
2298 them.
Google Python teamcfce3c32018-02-05 15:51:47 -05002299- Files and sockets that are shared throughout a program may inadvertently be
2300 read from or written to after logically being closed. If they are actually
2301 closed, attempts to read or write from them will throw exceptions, making
2302 the problem known sooner.
2303
2304Furthermore, while files and sockets are automatically closed when the file
Google Python team6271f3f2018-12-05 14:40:50 -08002305object is destructed, tying the lifetime of the file object to the state of the
2306file is poor practice:
Google Python teamcfce3c32018-02-05 15:51:47 -05002307
2308- There are no guarantees as to when the runtime will actually run the file's
2309 destructor. Different Python implementations use different memory management
2310 techniques, such as delayed Garbage Collection, which may increase the
2311 object's lifetime arbitrarily and indefinitely.
Google Python team6271f3f2018-12-05 14:40:50 -08002312- Unexpected references to the file, e.g. in globals or exception tracebacks,
2313 may keep it around longer than intended.
Google Python teamcfce3c32018-02-05 15:51:47 -05002314
2315The preferred way to manage files is using the ["with"
2316statement](http://docs.python.org/reference/compound_stmts.html#the-with-statement):
2317
Google Python team5b06d2d2018-11-18 18:21:51 -08002318```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002319with open("hello.txt") as hello_file:
2320 for line in hello_file:
2321 print(line)
2322```
2323
2324For file-like objects that do not support the "with" statement, use
2325`contextlib.closing()`:
2326
Google Python team5b06d2d2018-11-18 18:21:51 -08002327```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002328import contextlib
2329
2330with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
2331 for line in front_page:
2332 print(line)
2333```
2334
2335<a id="s3.12-todo-comments"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002336<a id="312-todo-comments"></a>
2337
2338<a id="todo"></a>
2339### 3.12 TODO Comments
Google Python teamcfce3c32018-02-05 15:51:47 -05002340
2341Use `TODO` comments for code that is temporary, a short-term solution, or
2342good-enough but not perfect.
2343
Google Python team6271f3f2018-12-05 14:40:50 -08002344A `TODO` comment begins with the string `TODO` in all caps and a parenthesized
Google Python teamcfce3c32018-02-05 15:51:47 -05002345name, e-mail address, or other identifier
Google Python team6271f3f2018-12-05 14:40:50 -08002346of the person or issue with the best context about the problem. This is followed
2347by an explanation of what there is to do.
2348
2349The purpose is to have a consistent `TODO` format that can be searched to find
2350out how to get more details. A `TODO` is not a commitment that the person
2351referenced will fix the problem. Thus when you create a
2352`TODO`, it is almost always your name
2353that is given.
Google Python teamcfce3c32018-02-05 15:51:47 -05002354
Google Python team5b06d2d2018-11-18 18:21:51 -08002355```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002356# TODO(kl@gmail.com): Use a "*" here for string repetition.
2357# TODO(Zeke) Change this to use relations.
2358```
2359
2360If your `TODO` is of the form "At a future date do something" make sure that you
2361either include a very specific date ("Fix by November 2009") or a very specific
2362event ("Remove this code when all clients can handle XML responses.").
2363
2364<a id="s3.13-imports-formatting"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002365<a id="313-imports-formatting"></a>
2366
Google Python teamcfce3c32018-02-05 15:51:47 -05002367<a id="imports-formatting"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002368### 3.13 Imports formatting
Google Python teamcfce3c32018-02-05 15:51:47 -05002369
2370Imports should be on separate lines.
2371
2372E.g.:
2373
Google Python team5b06d2d2018-11-18 18:21:51 -08002374```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002375Yes: import os
2376 import sys
2377```
2378
Google Python team5b06d2d2018-11-18 18:21:51 -08002379```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002380No: import os, sys
2381```
2382
Google Python teamad22a752018-11-15 07:47:37 -08002383
Google Python teamcfce3c32018-02-05 15:51:47 -05002384Imports are always put at the top of the file, just after any module comments
2385and docstrings and before module globals and constants. Imports should be
Google Python team6271f3f2018-12-05 14:40:50 -08002386grouped from most generic to least generic:
Google Python teamcfce3c32018-02-05 15:51:47 -05002387
Google Python team83a9e8d2019-10-10 00:40:18 -070023881. Python future import statements. For example:
2389
2390 ```python
2391 from __future__ import absolute_import
2392 from __future__ import division
2393 from __future__ import print_function
2394 ```
2395
2396 See [above](#from-future-imports) for more information about those.
2397
23982. Python standard library imports. For example:
Google Python teamcfce3c32018-02-05 15:51:47 -05002399
Google Python team5b06d2d2018-11-18 18:21:51 -08002400 ```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002401 import sys
2402 ```
2403
Google Python team83a9e8d2019-10-10 00:40:18 -070024043. [third-party](https://pypi.org/) module
2405 or package imports. For example:
Google Python teamcfce3c32018-02-05 15:51:47 -05002406
2407
Google Python team5b06d2d2018-11-18 18:21:51 -08002408 ```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002409 import tensorflow as tf
2410 ```
2411
Google Python team83a9e8d2019-10-10 00:40:18 -070024124. Code repository
Google Python teamcfce3c32018-02-05 15:51:47 -05002413 sub-package imports. For example:
2414
2415
Google Python team5b06d2d2018-11-18 18:21:51 -08002416 ```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002417 from otherproject.ai import mind
2418 ```
2419
Google Python team83a9e8d2019-10-10 00:40:18 -070024205. **Deprecated:** application-specific imports that are part of the same
Google Python teamcfce3c32018-02-05 15:51:47 -05002421 top level
2422 sub-package as this file. For example:
2423
2424
Google Python team5b06d2d2018-11-18 18:21:51 -08002425 ```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002426 from myproject.backend.hgwells import time_machine
2427 ```
2428
Google Python teamad22a752018-11-15 07:47:37 -08002429 You may find older Google Python Style code doing this, but it is no longer
Google Python team83a9e8d2019-10-10 00:40:18 -07002430 required. **New code is encouraged not to bother with this.** Simply treat
2431 application-specific sub-package imports the same as other sub-package
2432 imports.
Google Python teamad22a752018-11-15 07:47:37 -08002433
2434
Google Python teamcfce3c32018-02-05 15:51:47 -05002435Within each grouping, imports should be sorted lexicographically, ignoring case,
2436according to each module's full package path. Code may optionally place a blank
2437line between import sections.
2438
Google Python team5b06d2d2018-11-18 18:21:51 -08002439```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002440import collections
Google Python teamad22a752018-11-15 07:47:37 -08002441import queue
Google Python teamcfce3c32018-02-05 15:51:47 -05002442import sys
2443
Google Python teamad22a752018-11-15 07:47:37 -08002444from absl import app
2445from absl import flags
2446import bs4
Google Python teamcfce3c32018-02-05 15:51:47 -05002447import cryptography
2448import tensorflow as tf
2449
Google Python teamad22a752018-11-15 07:47:37 -08002450from book.genres import scifi
2451from myproject.backend.hgwells import time_machine
2452from myproject.backend.state_machine import main_loop
Google Python teamcfce3c32018-02-05 15:51:47 -05002453from otherproject.ai import body
2454from otherproject.ai import mind
2455from otherproject.ai import soul
2456
Google Python teamad22a752018-11-15 07:47:37 -08002457# Older style code may have these imports down here instead:
2458#from myproject.backend.hgwells import time_machine
2459#from myproject.backend.state_machine import main_loop
Google Python teamcfce3c32018-02-05 15:51:47 -05002460```
2461
2462
2463<a id="s3.14-statements"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002464<a id="314-statements"></a>
2465
Google Python teamcfce3c32018-02-05 15:51:47 -05002466<a id="statements"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002467### 3.14 Statements
Google Python teamcfce3c32018-02-05 15:51:47 -05002468
2469Generally only one statement per line.
2470
2471However, you may put the result of a test on the same line as the test only if
2472the entire statement fits on one line. In particular, you can never do so with
2473`try`/`except` since the `try` and `except` can't both fit on the same line, and
2474you can only do so with an `if` if there is no `else`.
2475
Google Python team5b06d2d2018-11-18 18:21:51 -08002476```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002477Yes:
2478
2479 if foo: bar(foo)
2480```
2481
Google Python team5b06d2d2018-11-18 18:21:51 -08002482```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002483No:
2484
2485 if foo: bar(foo)
2486 else: baz(foo)
2487
2488 try: bar(foo)
2489 except ValueError: baz(foo)
2490
2491 try:
2492 bar(foo)
2493 except ValueError: baz(foo)
2494```
2495
2496<a id="s3.15-access-control"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002497<a id="315-access-control"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05002498<a id="access-control"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002499
2500<a id="accessors"></a>
2501### 3.15 Accessors
Google Python teamcfce3c32018-02-05 15:51:47 -05002502
Google Python team6271f3f2018-12-05 14:40:50 -08002503If an accessor function would be trivial, you should use public variables
2504instead of accessor functions to avoid the extra cost of function calls in
2505Python. When more functionality is added you can use `property` to keep the
2506syntax consistent.
Google Python teamcfce3c32018-02-05 15:51:47 -05002507
2508On the other hand, if access is more complex, or the cost of accessing the
2509variable is significant, you should use function calls (following the
2510[Naming](#s3.16-naming) guidelines) such as `get_foo()` and
2511`set_foo()`. If the past behavior allowed access through a property, do not
2512bind the new accessor functions to the property. Any code still attempting to
2513access the variable by the old method should break visibly so they are made
2514aware of the change in complexity.
2515
2516<a id="s3.16-naming"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002517<a id="316-naming"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05002518
Google Python team83a9e8d2019-10-10 00:40:18 -07002519<a id="naming"></a>
2520### 3.16 Naming
2521
2522`module_name`, `package_name`, `ClassName`, `method_name`, `ExceptionName`,
2523`function_name`, `GLOBAL_CONSTANT_NAME`, `global_var_name`, `instance_var_name`,
2524`function_parameter_name`, `local_var_name`.
2525
Google Python teamcfce3c32018-02-05 15:51:47 -05002526
2527Function names, variable names, and filenames should be descriptive; eschew
2528abbreviation. In particular, do not use abbreviations that are ambiguous or
2529unfamiliar to readers outside your project, and do not abbreviate by deleting
2530letters within a word.
2531
2532Always use a `.py` filename extension. Never use dashes.
2533
2534<a id="s3.16.1-names-to-avoid"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002535<a id="3161-names-to-avoid"></a>
2536
Google Python teamcfce3c32018-02-05 15:51:47 -05002537<a id="names-to-avoid"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002538#### 3.16.1 Names to Avoid
Google Python teamcfce3c32018-02-05 15:51:47 -05002539
2540- single character names except for counters or iterators. You may use "e" as
2541 an exception identifier in try/except statements.
2542- dashes (`-`) in any package/module name
2543- `__double_leading_and_trailing_underscore__` names (reserved by Python)
2544
2545<a id="s3.16.2-naming-conventions"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002546<a id="3162-naming-convention"></a>
2547
Google Python teamcfce3c32018-02-05 15:51:47 -05002548<a id="naming-conventions"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002549#### 3.16.2 Naming Conventions
Google Python teamcfce3c32018-02-05 15:51:47 -05002550
Google Python team6271f3f2018-12-05 14:40:50 -08002551- "Internal" means internal to a module, or protected or private within a
Google Python teamcfce3c32018-02-05 15:51:47 -05002552 class.
2553
2554- Prepending a single underscore (`_`) has some support for protecting module
2555 variables and functions (not included with `from module import *`). While
2556 prepending a double underscore (`__` aka "dunder") to an instance variable
2557 or method effectively makes the variable or method private to its class
2558 (using name mangling) we discourage its use as it impacts readability and
2559 testability and isn't *really* private.
2560
2561- Place related classes and top-level functions together in a
2562 module.
2563 Unlike Java, there is no need to limit yourself to one class per module.
2564
2565- Use CapWords for class names, but lower\_with\_under.py for module names.
2566 Although there are some old modules named CapWords.py, this is now
2567 discouraged because it's confusing when the module happens to be named after
Google Python team6271f3f2018-12-05 14:40:50 -08002568 a class. ("wait -- did I write `import StringIO` or `from StringIO import
2569 StringIO`?")
Google Python teamcfce3c32018-02-05 15:51:47 -05002570
2571- Underscores may appear in *unittest* method names starting with `test` to
2572 separate logical components of the name, even if those components use
2573 CapWords. One possible pattern is `test<MethodUnderTest>_<state>`; for
2574 example `testPop_EmptyStack` is okay. There is no One Correct Way to name
2575 test methods.
2576
2577<a id="s3.16.3-file-naming"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002578<a id="3163-file-naming"></a>
2579
Google Python teamcfce3c32018-02-05 15:51:47 -05002580<a id="file-naming"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002581#### 3.16.3 File Naming
Google Python teamcfce3c32018-02-05 15:51:47 -05002582
2583Python filenames must have a `.py` extension and must not contain dashes (`-`).
2584This allows them to be imported and unittested. If you want an executable to be
2585accessible without the extension, use a symbolic link or a simple bash wrapper
2586containing `exec "$0.py" "$@"`.
2587
2588<a id="s3.16.4-guidelines-derived-from-guidos-recommendations"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002589<a id="3164-guidelines-derived-from-guidos-recommendations"></a>
2590
Google Python teamcfce3c32018-02-05 15:51:47 -05002591<a id="guidelines-derived-from-guidos-recommendations"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002592#### 3.16.4 Guidelines derived from Guido's Recommendations
Google Python teamcfce3c32018-02-05 15:51:47 -05002593
2594<table rules="all" border="1" summary="Guidelines from Guido's Recommendations"
2595 cellspacing="2" cellpadding="2">
2596
2597 <tr>
2598 <th>Type</th>
2599 <th>Public</th>
2600 <th>Internal</th>
2601 </tr>
2602
2603 <tr>
2604 <td>Packages</td>
2605 <td><code>lower_with_under</code></td>
2606 <td></td>
2607 </tr>
2608
2609 <tr>
2610 <td>Modules</td>
2611 <td><code>lower_with_under</code></td>
2612 <td><code>_lower_with_under</code></td>
2613 </tr>
2614
2615 <tr>
2616 <td>Classes</td>
2617 <td><code>CapWords</code></td>
2618 <td><code>_CapWords</code></td>
2619 </tr>
2620
2621 <tr>
2622 <td>Exceptions</td>
2623 <td><code>CapWords</code></td>
2624 <td></td>
2625 </tr>
2626
leVirvec16cbe72018-06-17 11:58:16 +08002627 <tr>
Google Python teamcfce3c32018-02-05 15:51:47 -05002628 <td>Functions</td>
2629 <td><code>lower_with_under()</code></td>
2630 <td><code>_lower_with_under()</code></td>
2631 </tr>
2632
2633 <tr>
2634 <td>Global/Class Constants</td>
2635 <td><code>CAPS_WITH_UNDER</code></td>
2636 <td><code>_CAPS_WITH_UNDER</code></td>
2637 </tr>
2638
2639 <tr>
2640 <td>Global/Class Variables</td>
2641 <td><code>lower_with_under</code></td>
2642 <td><code>_lower_with_under</code></td>
2643 </tr>
2644
2645 <tr>
2646 <td>Instance Variables</td>
2647 <td><code>lower_with_under</code></td>
2648 <td><code>_lower_with_under</code> (protected)</td>
2649 </tr>
2650
leVirvec16cbe72018-06-17 11:58:16 +08002651 <tr>
Google Python teamcfce3c32018-02-05 15:51:47 -05002652 <td>Method Names</td>
2653 <td><code>lower_with_under()</code></td>
2654 <td><code>_lower_with_under()</code> (protected)</td>
2655 </tr>
2656
2657 <tr>
2658 <td>Function/Method Parameters</td>
2659 <td><code>lower_with_under</code></td>
2660 <td></td>
2661 </tr>
2662
2663 <tr>
2664 <td>Local Variables</td>
2665 <td><code>lower_with_under</code></td>
2666 <td></td>
2667 </tr>
2668
2669</table>
2670
2671While Python supports making things private by using a leading double underscore
Google Python team6271f3f2018-12-05 14:40:50 -08002672`__` (aka. "dunder") prefix on a name, this is discouraged. Prefer the use of a
2673single underscore. They are easier to type, read, and to access from small
2674unittests. Lint warnings take care of invalid access to protected members.
Google Python teamcfce3c32018-02-05 15:51:47 -05002675
2676
2677<a id="s3.17-main"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002678<a id="317-main"></a>
2679
Google Python teamcfce3c32018-02-05 15:51:47 -05002680<a id="main"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002681### 3.17 Main
Google Python teamcfce3c32018-02-05 15:51:47 -05002682
2683Even a file meant to be used as an executable should be importable and a mere
2684import should not have the side effect of executing the program's main
2685functionality. The main functionality should be in a `main()` function.
2686
2687In Python, `pydoc` as well as unit tests require modules to be importable. Your
2688code should always check `if __name__ == '__main__'` before executing your main
2689program so that the main program is not executed when the module is imported.
2690
Google Python team5b06d2d2018-11-18 18:21:51 -08002691```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002692def main():
2693 ...
2694
2695if __name__ == '__main__':
2696 main()
2697```
2698
2699All code at the top level will be executed when the module is imported. Be
2700careful not to call functions, create objects, or perform other operations that
2701should not be executed when the file is being `pydoc`ed.
2702
2703<a id="s3.18-function-length"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002704<a id="318-function-length"></a>
2705
Google Python teamcfce3c32018-02-05 15:51:47 -05002706<a id="function-length"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002707### 3.18 Function length
Google Python teamcfce3c32018-02-05 15:51:47 -05002708
2709Prefer small and focused functions.
2710
2711We recognize that long functions are sometimes appropriate, so no hard limit is
2712placed on function length. If a function exceeds about 40 lines, think about
2713whether it can be broken up without harming the structure of the program.
2714
2715Even if your long function works perfectly now, someone modifying it in a few
2716months may add new behavior. This could result in bugs that are hard to find.
2717Keeping your functions short and simple makes it easier for other people to read
2718and modify your code.
2719
2720You could find long and complicated functions when working with
2721some code. Do not be intimidated by modifying existing code: if working with such
2722a function proves to be difficult, you find that errors are hard to debug, or
2723you want to use a piece of it in several different contexts, consider breaking
2724up the function into smaller and more manageable pieces.
2725
2726<a id="s3.19-type-annotations"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002727<a id="319-type-annotations"></a>
2728
Google Python teamcfce3c32018-02-05 15:51:47 -05002729<a id="type-annotations"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002730### 3.19 Type Annotations
2731
2732<a id="s3.19.1-general"></a>
2733<a id="3191-general-rules"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05002734
2735<a id="typing-general"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002736#### 3.19.1 General Rules
Google Python teamcfce3c32018-02-05 15:51:47 -05002737
2738* Familiarize yourself with [PEP-484](https://www.python.org/dev/peps/pep-0484/).
Google Python teamad22a752018-11-15 07:47:37 -08002739* In methods, only annotate `self`, or `cls` if it is necessary for proper type
2740 information. e.g., `@classmethod def create(cls: Type[T]) -> T: return cls()`
Google Python teamcfce3c32018-02-05 15:51:47 -05002741* If any other variable or a returned type should not be expressed, use `Any`.
2742* You are not required to annotate all the functions in a module.
2743 - At least annotate your public APIs.
2744 - Use judgment to get to a good balance between safety and clarity on the
2745 one hand, and flexibility on the other.
2746 - Annotate code that is prone to type-related errors (previous bugs or
2747 complexity).
2748 - Annotate code that is hard to understand.
2749 - Annotate code as it becomes stable from a types perspective. In many
2750 cases, you can annotate all the functions in mature code without losing
2751 too much flexibility.
2752
2753
2754<a id="s3.19.2-line-breaking"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002755<a id="3192-line-breaking"></a>
2756
Google Python teamcfce3c32018-02-05 15:51:47 -05002757<a id="typing-line-breaking"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002758#### 3.19.2 Line Breaking
Google Python teamcfce3c32018-02-05 15:51:47 -05002759
Google Python teamad22a752018-11-15 07:47:37 -08002760Try to follow the existing [indentation](#indentation) rules.
Google Python teamcfce3c32018-02-05 15:51:47 -05002761
Google Python teamad22a752018-11-15 07:47:37 -08002762After annotating, many function signatures will become "one parameter per line".
Google Python teamcfce3c32018-02-05 15:51:47 -05002763
Google Python team5b06d2d2018-11-18 18:21:51 -08002764```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002765def my_method(self,
2766 first_var: int,
2767 second_var: Foo,
2768 third_var: Optional[Bar]) -> int:
2769 ...
2770```
2771
Google Python teamad22a752018-11-15 07:47:37 -08002772Always prefer breaking between variables, and not for example between variable
2773names and type annotations. However, if everything fits on the same line,
2774go for it.
Google Python teamcfce3c32018-02-05 15:51:47 -05002775
Google Python team5b06d2d2018-11-18 18:21:51 -08002776```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002777def my_method(self, first_var: int) -> int:
2778 ...
2779```
2780
2781If the combination of the function name, the last parameter, and the return type
2782is too long, indent by 4 in a new line.
2783
Google Python team5b06d2d2018-11-18 18:21:51 -08002784```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002785def my_method(
2786 self, first_var: int) -> Tuple[MyLongType1, MyLongType1]:
2787 ...
2788```
2789
2790When the return type does not fit on the same line as the last parameter, the
2791preferred way is to indent the parameters by 4 on a new line and align the
2792closing parenthesis with the def.
2793
Google Python team5b06d2d2018-11-18 18:21:51 -08002794```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002795Yes:
2796def my_method(
Google Python team83a9e8d2019-10-10 00:40:18 -07002797 self, other_arg: Optional[MyLongType]
Google Python teamcfce3c32018-02-05 15:51:47 -05002798) -> Dict[OtherLongType, MyLongType]:
2799 ...
2800```
2801
2802`pylint` allows you to move the closing parenthesis to a new line and align
2803with the opening one, but this is less readable.
2804
Google Python team5b06d2d2018-11-18 18:21:51 -08002805```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002806No:
2807def my_method(self,
Google Python team83a9e8d2019-10-10 00:40:18 -07002808 other_arg: Optional[MyLongType]
Google Python teamcfce3c32018-02-05 15:51:47 -05002809 ) -> Dict[OtherLongType, MyLongType]:
2810 ...
2811```
2812
2813As in the examples above, prefer not to break types. However, sometimes they are
2814too long to be on a single line (try to keep sub-types unbroken).
2815
Google Python team5b06d2d2018-11-18 18:21:51 -08002816```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002817def my_method(
2818 self,
2819 first_var: Tuple[List[MyLongType1],
2820 List[MyLongType2]],
2821 second_var: List[Dict[
2822 MyLongType3, MyLongType4]]) -> None:
2823 ...
2824```
2825
2826If a single name and type is too long, consider using an
2827[alias](#typing-aliases) for the type. The last resort is to break after the
2828colon and indent by 4.
2829
Google Python team5b06d2d2018-11-18 18:21:51 -08002830```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002831Yes:
2832def my_function(
2833 long_variable_name:
2834 long_module_name.LongTypeName,
2835) -> None:
2836 ...
2837```
2838
Google Python team5b06d2d2018-11-18 18:21:51 -08002839```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002840No:
2841def my_function(
2842 long_variable_name: long_module_name.
2843 LongTypeName,
2844) -> None:
2845 ...
2846```
2847
2848<a id="s3.19.3-forward-declarations"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002849<a id="3193-forward-declarations"></a>
2850
2851<a id="forward-declarations"></a>
2852#### 3.19.3 Forward Declarations
Google Python teamcfce3c32018-02-05 15:51:47 -05002853
2854If you need to use a class name from the same module that is not yet defined --
2855for example, if you need the class inside the class declaration, or if you use a
2856class that is defined below -- use a string for the class name.
2857
Google Python team5b06d2d2018-11-18 18:21:51 -08002858```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002859class MyClass(object):
2860
2861 def __init__(self,
2862 stack: List["MyClass"]) -> None:
2863```
2864
2865<a id="s3.19.4-default-values"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002866<a id="3194-default-values"></a>
2867
Google Python teamcfce3c32018-02-05 15:51:47 -05002868<a id="typing-default-values"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002869#### 3.19.4 Default Values
Google Python teamcfce3c32018-02-05 15:51:47 -05002870
Google Python team6271f3f2018-12-05 14:40:50 -08002871As per
2872[PEP-008](https://www.python.org/dev/peps/pep-0008/#other-recommendations), use
2873spaces around the `=` _only_ for arguments that have both a type annotation and
2874a default value.
Google Python teamcfce3c32018-02-05 15:51:47 -05002875
Google Python team5b06d2d2018-11-18 18:21:51 -08002876```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002877Yes:
2878def func(a: int = 0) -> int:
2879 ...
2880```
Google Python team5b06d2d2018-11-18 18:21:51 -08002881```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002882No:
2883def func(a:int=0) -> int:
2884 ...
2885```
2886
2887<a id="s3.19.5-none-type"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002888<a id="3195-nonetype"></a>
2889
Google Python teamcfce3c32018-02-05 15:51:47 -05002890<a id="none-type"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002891#### 3.19.5 NoneType
Google Python teamcfce3c32018-02-05 15:51:47 -05002892
2893In the Python type system, `NoneType` is a "first class" type, and for typing
2894purposes, `None` is an alias for `NoneType`. If an argument can be `None`, it
2895has to be declared! You can use `Union`, but if there is only one other type,
Google Python teamad22a752018-11-15 07:47:37 -08002896use `Optional`.
2897
2898Use explicit `Optional` instead of implicit `Optional`. Earlier versions of PEP
2899484 allowed `a: Text = None` to be interpretted as `a: Optional[Text] = None`,
2900but that is no longer the preferred behavior.
Google Python teamcfce3c32018-02-05 15:51:47 -05002901
Google Python team5b06d2d2018-11-18 18:21:51 -08002902```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002903Yes:
Google Python teamad22a752018-11-15 07:47:37 -08002904def func(a: Optional[Text], b: Optional[Text] = None) -> Text:
2905 ...
2906def multiple_nullable_union(a: Union[None, Text, int]) -> Text
Google Python teamcfce3c32018-02-05 15:51:47 -05002907 ...
2908```
2909
Google Python team5b06d2d2018-11-18 18:21:51 -08002910```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002911No:
Google Python teamad22a752018-11-15 07:47:37 -08002912def nullable_union(a: Union[None, Text]) -> Text:
Google Python teamcfce3c32018-02-05 15:51:47 -05002913 ...
Google Python teamad22a752018-11-15 07:47:37 -08002914def implicit_optional(a: Text = None) -> Text:
Google Python teamcfce3c32018-02-05 15:51:47 -05002915 ...
2916```
2917
2918<a id="s3.19.6-aliases"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002919<a id="3196-type-aliases"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05002920<a id="typing-aliases"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002921
2922<a id="type-aliases"></a>
2923#### 3.19.6 Type Aliases
Google Python teamcfce3c32018-02-05 15:51:47 -05002924
2925You can declare aliases of complex types. The name of an alias should be
Google Python teamfdc20e82018-11-28 10:15:08 -08002926CapWorded. If the alias is used only in this module, it should be
Google Python teamcfce3c32018-02-05 15:51:47 -05002927\_Private.
2928
Google Python team83a9e8d2019-10-10 00:40:18 -07002929For example, if the name of the module together with the name of the type is too
2930long:
Google Python teamcfce3c32018-02-05 15:51:47 -05002931
Google Python team5b06d2d2018-11-18 18:21:51 -08002932```python
Google Python teamfdc20e82018-11-28 10:15:08 -08002933_ShortName = module_with_long_name.TypeWithLongName
2934ComplexMap = Mapping[Text, List[Tuple[int, int]]]
Google Python teamcfce3c32018-02-05 15:51:47 -05002935```
2936
2937Other examples are complex nested types and multiple return variables from a
2938function (as a tuple).
2939
2940<a id="s3.19.7-ignore"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002941<a id="3197-ignoring-types"></a>
2942
Google Python teamcfce3c32018-02-05 15:51:47 -05002943<a id="typing-ignore"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002944#### 3.19.7 Ignoring Types
Google Python teamcfce3c32018-02-05 15:51:47 -05002945
2946You can disable type checking on a line with the special comment
2947`# type: ignore`.
2948
2949`pytype` has a disable option for specific errors (similar to lint):
2950
Google Python team5b06d2d2018-11-18 18:21:51 -08002951```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002952# pytype: disable=attribute-error
2953```
2954
2955<a id="s3.19.8-comments"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002956<a id="3198-typing-internal-variables"></a>
2957
2958<a id="typing-variables"></a>
2959#### 3.19.8 Typing Variables
Google Python teamcfce3c32018-02-05 15:51:47 -05002960
2961If an internal variable has a type that is hard or impossible to infer, you can
Google Python team83a9e8d2019-10-10 00:40:18 -07002962specify its type in a couple ways.
Google Python teamcfce3c32018-02-05 15:51:47 -05002963
Google Python team83a9e8d2019-10-10 00:40:18 -07002964<a id="type-comments"></a>
2965[*Type Comments:*](#type-comments)
2966: Use a `# type:` comment on the end of the line
2967
2968 ```python
2969 a = SomeUndecoratedFunction() # type: Foo
2970 ```
2971
2972[*Annotated Assignments*](#annotated-assignments)
2973: Use a colon and type between the variable name and value, as with function
2974 arguments.
2975
2976 ```python
2977 a: Foo = SomeUndecoratedFunction()
2978 ```
2979
Google Python teamcfce3c32018-02-05 15:51:47 -05002980<a id="s3.19.9-tuples"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002981<a id="3199-tuples-vs-lists"></a>
2982
Google Python teamcfce3c32018-02-05 15:51:47 -05002983<a id="typing-tuples"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002984#### 3.19.9 Tuples vs Lists
Google Python teamcfce3c32018-02-05 15:51:47 -05002985
2986Unlike Lists, which can only have a single type, Tuples can have either a single
2987repeated type or a set number of elements with different types. The latter is
2988commonly used as return type from a function.
2989
Google Python team5b06d2d2018-11-18 18:21:51 -08002990```python
Google Python teamcfce3c32018-02-05 15:51:47 -05002991a = [1, 2, 3] # type: List[int]
2992b = (1, 2, 3) # type: Tuple[int, ...]
Google Python teamad22a752018-11-15 07:47:37 -08002993c = (1, "2", 3.5) # type: Tuple[int, Text, float]
Google Python teamcfce3c32018-02-05 15:51:47 -05002994```
2995
2996<a id="s3.19.10-type-var"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002997<a id="31910-typevar"></a>
Google Python teamcfce3c32018-02-05 15:51:47 -05002998<a id="typing-type-var"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07002999
3000<a id="typevars"></a>
3001#### 3.19.10 TypeVars
Google Python teamcfce3c32018-02-05 15:51:47 -05003002
3003The Python type system has
3004[generics](https://www.python.org/dev/peps/pep-0484/#generics). The factory
3005function `TypeVar` is a common way to use them.
3006
3007Example:
3008
Google Python team5b06d2d2018-11-18 18:21:51 -08003009```python
Google Python teamcfce3c32018-02-05 15:51:47 -05003010from typing import List, TypeVar
3011T = TypeVar("T")
3012...
3013def next(l: List[T]) -> T:
3014 return l.pop()
3015```
3016
3017A TypeVar can be constrained:
3018
Google Python team5b06d2d2018-11-18 18:21:51 -08003019```python
Google Python teamad22a752018-11-15 07:47:37 -08003020AddableType = TypeVar("AddableType", int, float, Text)
Google Python teamcfce3c32018-02-05 15:51:47 -05003021def add(a: AddableType, b: AddableType) -> AddableType:
3022 return a + b
3023```
3024
3025A common predefined type variable in the `typing` module is `AnyStr`. Use it for
Google Python teamad22a752018-11-15 07:47:37 -08003026multiple annotations that can be `bytes` or `unicode` and must all be the same
3027type.
Google Python teamcfce3c32018-02-05 15:51:47 -05003028
Google Python team5b06d2d2018-11-18 18:21:51 -08003029```python
Google Python teamad22a752018-11-15 07:47:37 -08003030from typing import AnyStr
3031def check_length(x: AnyStr) -> AnyStr:
3032 if len(x) <= 42:
3033 return x
3034 raise ValueError()
Google Python teamcfce3c32018-02-05 15:51:47 -05003035```
Google Python teamad22a752018-11-15 07:47:37 -08003036
Google Python teamcfce3c32018-02-05 15:51:47 -05003037<a id="s3.19.11-strings"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07003038<a id="31911-string-types"></a>
Google Python team6271f3f2018-12-05 14:40:50 -08003039
Google Python team83a9e8d2019-10-10 00:40:18 -07003040<a id="typing-strings"></a>
3041#### 3.19.11 String types
Google Python teamcfce3c32018-02-05 15:51:47 -05003042
Google Python team5b06d2d2018-11-18 18:21:51 -08003043The proper type for annotating strings depends on what versions of Python the
3044code is intended for.
Google Python teamcfce3c32018-02-05 15:51:47 -05003045
Google Python team5b06d2d2018-11-18 18:21:51 -08003046For Python 3 only code, prefer to use `str`. `Text` is also acceptable. Be
3047consistent in using one or the other.
3048
3049For Python 2 compatible code, use `Text`. In some rare cases, `str` may make
Google Python team83a9e8d2019-10-10 00:40:18 -07003050sense; typically to aid compatibility when the return types aren't the same
Google Python team5b06d2d2018-11-18 18:21:51 -08003051between the two Python versions. Avoid using `unicode`: it doesn't exist in
3052Python 3.
3053
Google Python team83a9e8d2019-10-10 00:40:18 -07003054The reason this discrepancy exists is because `str` means different things
Google Python team5b06d2d2018-11-18 18:21:51 -08003055depending on the Python version.
3056
3057```python
Google Python teamcfce3c32018-02-05 15:51:47 -05003058No:
Google Python team5b06d2d2018-11-18 18:21:51 -08003059def py2_code(x: str) -> unicode:
Google Python teamcfce3c32018-02-05 15:51:47 -05003060 ...
3061```
3062
Google Python team5b06d2d2018-11-18 18:21:51 -08003063For code that deals with binary data, use `bytes`.
Google Python teamcfce3c32018-02-05 15:51:47 -05003064
Google Python team5b06d2d2018-11-18 18:21:51 -08003065```python
3066def deals_with_binary_data(x: bytes) -> bytes:
Google Python teamcfce3c32018-02-05 15:51:47 -05003067 ...
3068```
3069
Google Python team5b06d2d2018-11-18 18:21:51 -08003070For Python 2 compatible code that processes text data (`str` or `unicode` in
3071Python 2, `str` in Python 3), use `Text`. For Python 3 only code that process
3072text data, prefer `str`.
Google Python teamcfce3c32018-02-05 15:51:47 -05003073
Google Python team5b06d2d2018-11-18 18:21:51 -08003074```python
Google Python teamcfce3c32018-02-05 15:51:47 -05003075from typing import Text
3076...
Google Python team5b06d2d2018-11-18 18:21:51 -08003077def py2_compatible(x: Text) -> Text:
3078 ...
3079def py3_only(x: str) -> str:
Google Python teamcfce3c32018-02-05 15:51:47 -05003080 ...
3081```
3082
Google Python team5b06d2d2018-11-18 18:21:51 -08003083If the type can be either bytes or text, use `Union`, with the appropriate text
3084type.
Google Python teamcfce3c32018-02-05 15:51:47 -05003085
Google Python team5b06d2d2018-11-18 18:21:51 -08003086```python
Google Python teamcfce3c32018-02-05 15:51:47 -05003087from typing import Text, Union
3088...
Google Python team5b06d2d2018-11-18 18:21:51 -08003089def py2_compatible(x: Union[bytes, Text]) -> Union[bytes, Text]:
3090 ...
3091def py3_only(x: Union[bytes, str]) -> Union[bytes, str]:
Google Python teamcfce3c32018-02-05 15:51:47 -05003092 ...
3093```
3094
3095If all the string types of a function are always the same, for example if the
3096return type is the same as the argument type in the code above, use
3097[AnyStr](#typing-type-var).
3098
3099Writing it like this will simplify the process of porting the code to Python 3.
3100
3101<a id="s3.19.12-imports"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07003102<a id="31912-imports-for-typing"></a>
3103
Google Python teamcfce3c32018-02-05 15:51:47 -05003104<a id="typing-imports"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07003105#### 3.19.12 Imports For Typing
Google Python teamcfce3c32018-02-05 15:51:47 -05003106
3107For classes from the `typing` module, always import the class itself. You are
3108explicitly allowed to import multiple specific classes on one line from the
3109`typing` module. Ex:
3110
Google Python team5b06d2d2018-11-18 18:21:51 -08003111```python
Google Python teamcfce3c32018-02-05 15:51:47 -05003112from typing import Any, Dict, Optional
3113```
3114
3115Given that this way of importing from `typing` adds items to the local
3116namespace, any names in `typing` should be treated similarly to keywords, and
3117not be defined in your Python code, typed or not. If there is a collision
3118between a type and an existing name in a module, import it using
3119`import x as y`.
3120
Google Python team5b06d2d2018-11-18 18:21:51 -08003121```python
Google Python teamcfce3c32018-02-05 15:51:47 -05003122from typing import Any as AnyType
3123```
3124
Google Python teamad22a752018-11-15 07:47:37 -08003125<a id="s3.19.13-conditional-imports"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07003126<a id="31913-conditional-imports"></a>
3127
Google Python teamad22a752018-11-15 07:47:37 -08003128<a id="typing-conditional-imports"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07003129#### 3.19.13 Conditional Imports
Google Python teamcfce3c32018-02-05 15:51:47 -05003130
Google Python team6271f3f2018-12-05 14:40:50 -08003131Use conditional imports only in exceptional cases where the additional imports
3132needed for type checking must be avoided at runtime. This pattern is
3133discouraged; alternatives such as refactoring the code to allow top level
3134imports should be preferred.
Google Python teamad22a752018-11-15 07:47:37 -08003135
3136Imports that are needed only for type annotations can be placed within an
3137`if TYPE_CHECKING:` block.
3138
3139- Conditionally imported types need to be referenced as strings, to be
3140 forward compatible with Python 3.6 where the annotation expressions are
3141 actually evaluated.
Google Python teamcfce3c32018-02-05 15:51:47 -05003142- Only entities that are used solely for typing should be defined here; this
3143 includes aliases. Otherwise it will be a runtime error, as the module will
3144 not be imported at runtime.
3145- The block should be right after all the normal imports.
3146- There should be no empty lines in the typing imports list.
Google Python teamad22a752018-11-15 07:47:37 -08003147- Sort this list as if it were a regular imports list.
Google Python teamcfce3c32018-02-05 15:51:47 -05003148
Google Python team5b06d2d2018-11-18 18:21:51 -08003149```python
Google Python teamcfce3c32018-02-05 15:51:47 -05003150import typing
Google Python teamcfce3c32018-02-05 15:51:47 -05003151if typing.TYPE_CHECKING:
Google Python teamad22a752018-11-15 07:47:37 -08003152 import sketch
3153def f(x: "sketch.Sketch"): ...
Google Python teamcfce3c32018-02-05 15:51:47 -05003154```
3155
Google Python teamad22a752018-11-15 07:47:37 -08003156<a id="s3.19.14-circular-deps"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07003157<a id="31914-circular-dependencies"></a>
3158
Google Python teamcfce3c32018-02-05 15:51:47 -05003159<a id="typing-circular-deps"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07003160#### 3.19.14 Circular Dependencies
Google Python teamcfce3c32018-02-05 15:51:47 -05003161
3162Circular dependencies that are caused by typing are code smells. Such code is a
3163good candidate for refactoring. Although technically it is possible to keep
3164circular dependencies, the [build system](#typing-build-deps) will not let you
3165do so because each module has to depend on the other.
3166
3167Replace modules that create circular dependency imports with `Any`. Set an
3168[alias](#typing-aliases) with a meaningful name, and use the real type name from
3169this module (any attribute of Any is Any). Alias definitions should be separated
3170from the last import by one line.
3171
Google Python team5b06d2d2018-11-18 18:21:51 -08003172```python
Google Python teamcfce3c32018-02-05 15:51:47 -05003173from typing import Any
3174
3175some_mod = Any # some_mod.py imports this module.
3176...
3177
3178def my_method(self, var: some_mod.SomeType) -> None:
3179 ...
3180```
3181
Google Python teamad22a752018-11-15 07:47:37 -08003182<a id="typing-generics"></a>
3183<a id="s3.19.15-generics"></a>
Google Python team83a9e8d2019-10-10 00:40:18 -07003184<a id="31915-generics"></a>
Google Python teamad22a752018-11-15 07:47:37 -08003185
Google Python team83a9e8d2019-10-10 00:40:18 -07003186<a id="generics"></a>
3187#### 3.19.15 Generics
Google Python teamad22a752018-11-15 07:47:37 -08003188
3189When annotating, prefer to specify type parameters for generic types; otherwise,
3190[the generics' parameters will be assumed to be `Any`](https://www.python.org/dev/peps/pep-0484/#the-any-type).
3191
Google Python team5b06d2d2018-11-18 18:21:51 -08003192```python
Google Python teamad22a752018-11-15 07:47:37 -08003193def get_names(employee_ids: List[int]) -> Dict[int, Any]:
3194 ...
3195```
3196
Google Python team5b06d2d2018-11-18 18:21:51 -08003197```python
Google Python teamad22a752018-11-15 07:47:37 -08003198# These are both interpreted as get_names(employee_ids: List[Any]) -> Dict[Any, Any]
3199def get_names(employee_ids: list) -> Dict:
3200 ...
3201
3202def get_names(employee_ids: List) -> Dict:
3203 ...
3204```
3205
3206If the best type parameter for a generic is `Any`, make it explicit, but
3207remember that in many cases [`TypeVar`](#typing-type-var) might be more
3208appropriate:
3209
Google Python team5b06d2d2018-11-18 18:21:51 -08003210```python
Google Python teamad22a752018-11-15 07:47:37 -08003211def get_names(employee_ids: List[Any]) -> Dict[Any, Text]:
3212 """Returns a mapping from employee ID to employee name for given IDs."""
3213```
3214
Google Python team5b06d2d2018-11-18 18:21:51 -08003215```python
Google Python teamad22a752018-11-15 07:47:37 -08003216T = TypeVar('T')
3217def get_names(employee_ids: List[T]) -> Dict[T, Text]:
3218 """Returns a mapping from employee ID to employee name for given IDs."""
3219```
3220
Google Python teamcfce3c32018-02-05 15:51:47 -05003221
Google Python team83a9e8d2019-10-10 00:40:18 -07003222<a id="4-parting-words"></a>
3223
3224<a id="consistency"></a>
3225## 4 Parting Words
Google Python teamcfce3c32018-02-05 15:51:47 -05003226
3227*BE CONSISTENT*.
3228
3229If you're editing code, take a few minutes to look at the code around you and
3230determine its style. If they use spaces around all their arithmetic operators,
3231you should too. If their comments have little boxes of hash marks around them,
3232make your comments have little boxes of hash marks around them too.
3233
3234The point of having style guidelines is to have a common vocabulary of coding so
3235people can concentrate on what you're saying rather than on how you're saying
3236it. We present global style rules here so people know the vocabulary, but local
3237style is also important. If code you add to a file looks drastically different
3238from the existing code around it, it throws readers out of their rhythm when
3239they go to read it. Avoid this.
3240
Google Python team6271f3f2018-12-05 14:40:50 -08003241