readability-cli 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
guides/pyguide.md ADDED
@@ -0,0 +1,3709 @@
1
+ <!--
2
+ AUTHORS:
3
+ Prefer only GitHub-flavored Markdown in external text.
4
+ See README.md for details.
5
+ -->
6
+
7
+ # Google Python Style Guide
8
+
9
+ <!-- markdown="1" is required for GitHub Pages to render the TOC properly. -->
10
+
11
+ <details markdown="1">
12
+ <summary>Table of Contents</summary>
13
+
14
+ - [1 Background](#s1-background)
15
+ - [2 Python Language Rules](#s2-python-language-rules)
16
+ * [2.1 Lint](#s2.1-lint)
17
+ * [2.2 Imports](#s2.2-imports)
18
+ * [2.3 Packages](#s2.3-packages)
19
+ * [2.4 Exceptions](#s2.4-exceptions)
20
+ * [2.5 Mutable Global State](#s2.5-global-variables)
21
+ * [2.6 Nested/Local/Inner Classes and Functions](#s2.6-nested)
22
+ * [2.7 Comprehensions & Generator Expressions](#s2.7-comprehensions)
23
+ * [2.8 Default Iterators and Operators](#s2.8-default-iterators-and-operators)
24
+ * [2.9 Generators](#s2.9-generators)
25
+ * [2.10 Lambda Functions](#s2.10-lambda-functions)
26
+ * [2.11 Conditional Expressions](#s2.11-conditional-expressions)
27
+ * [2.12 Default Argument Values](#s2.12-default-argument-values)
28
+ * [2.13 Properties](#s2.13-properties)
29
+ * [2.14 True/False Evaluations](#s2.14-truefalse-evaluations)
30
+ * [2.16 Lexical Scoping](#s2.16-lexical-scoping)
31
+ * [2.17 Function and Method Decorators](#s2.17-function-and-method-decorators)
32
+ * [2.18 Threading](#s2.18-threading)
33
+ * [2.19 Power Features](#s2.19-power-features)
34
+ * [2.20 Modern Python: from \_\_future\_\_ imports](#s2.20-modern-python)
35
+ * [2.21 Type Annotated Code](#s2.21-type-annotated-code)
36
+ - [3 Python Style Rules](#s3-python-style-rules)
37
+ * [3.1 Semicolons](#s3.1-semicolons)
38
+ * [3.2 Line length](#s3.2-line-length)
39
+ * [3.3 Parentheses](#s3.3-parentheses)
40
+ * [3.4 Indentation](#s3.4-indentation)
41
+ + [3.4.1 Trailing commas in sequences of items?](#s3.4.1-trailing-commas)
42
+ * [3.5 Blank Lines](#s3.5-blank-lines)
43
+ * [3.6 Whitespace](#s3.6-whitespace)
44
+ * [3.7 Shebang Line](#s3.7-shebang-line)
45
+ * [3.8 Comments and Docstrings](#s3.8-comments-and-docstrings)
46
+ + [3.8.1 Docstrings](#s3.8.1-comments-in-doc-strings)
47
+ + [3.8.2 Modules](#s3.8.2-comments-in-modules)
48
+ + [3.8.2.1 Test modules](#s3.8.2.1-test-modules)
49
+ + [3.8.3 Functions and Methods](#s3.8.3-functions-and-methods)
50
+ + [3.8.3.1 Overridden Methods](#s3.8.3.1-overridden-methods)
51
+ + [3.8.4 Classes](#s3.8.4-comments-in-classes)
52
+ + [3.8.5 Block and Inline Comments](#s3.8.5-block-and-inline-comments)
53
+ + [3.8.6 Punctuation, Spelling, and Grammar](#s3.8.6-punctuation-spelling-and-grammar)
54
+ * [3.10 Strings](#s3.10-strings)
55
+ + [3.10.1 Logging](#s3.10.1-logging)
56
+ + [3.10.2 Error Messages](#s3.10.2-error-messages)
57
+ * [3.11 Files, Sockets, and similar Stateful Resources](#s3.11-files-sockets-closeables)
58
+ * [3.12 TODO Comments](#s3.12-todo-comments)
59
+ * [3.13 Imports formatting](#s3.13-imports-formatting)
60
+ * [3.14 Statements](#s3.14-statements)
61
+ * [3.15 Accessors](#s3.15-accessors)
62
+ * [3.16 Naming](#s3.16-naming)
63
+ + [3.16.1 Names to Avoid](#s3.16.1-names-to-avoid)
64
+ + [3.16.2 Naming Conventions](#s3.16.2-naming-conventions)
65
+ + [3.16.3 File Naming](#s3.16.3-file-naming)
66
+ + [3.16.4 Guidelines derived from Guido's Recommendations](#s3.16.4-guidelines-derived-from-guidos-recommendations)
67
+ * [3.17 Main](#s3.17-main)
68
+ * [3.18 Function length](#s3.18-function-length)
69
+ * [3.19 Type Annotations](#s3.19-type-annotations)
70
+ + [3.19.1 General Rules](#s3.19.1-general-rules)
71
+ + [3.19.2 Line Breaking](#s3.19.2-line-breaking)
72
+ + [3.19.3 Forward Declarations](#s3.19.3-forward-declarations)
73
+ + [3.19.4 Default Values](#s3.19.4-default-values)
74
+ + [3.19.5 NoneType](#s3.19.5-nonetype)
75
+ + [3.19.6 Type Aliases](#s3.19.6-type-aliases)
76
+ + [3.19.7 Ignoring Types](#s3.19.7-ignoring-types)
77
+ + [3.19.8 Typing Variables](#s3.19.8-typing-variables)
78
+ + [3.19.9 Tuples vs Lists](#s3.19.9-tuples-vs-lists)
79
+ + [3.19.10 Type variables](#s3.19.10-typevars)
80
+ + [3.19.11 String types](#s3.19.11-string-types)
81
+ + [3.19.12 Imports For Typing](#s3.19.12-imports-for-typing)
82
+ + [3.19.13 Conditional Imports](#s3.19.13-conditional-imports)
83
+ + [3.19.14 Circular Dependencies](#s3.19.14-circular-dependencies)
84
+ + [3.19.15 Generics](#s3.19.15-generics)
85
+ + [3.19.16 Build Dependencies](#s3.19.16-build-dependencies)
86
+ - [4 Parting Words](#4-parting-words)
87
+
88
+ </details>
89
+
90
+ <a id="s1-background"></a>
91
+ <a id="1-background"></a>
92
+
93
+ <a id="background"></a>
94
+ ## 1 Background
95
+
96
+ Python is the main dynamic language used at Google. This style guide is a list
97
+ of *dos and don'ts* for Python programs.
98
+
99
+ To help you format code correctly, we've created a [settings file for Vim](google_python_style.vim). For Emacs, the default settings should be fine.
100
+
101
+ Many teams use the [Black](https://github.com/psf/black) or [Pyink](https://github.com/google/pyink)
102
+ auto-formatter to avoid arguing over formatting.
103
+
104
+
105
+ <a id="s2-python-language-rules"></a>
106
+ <a id="2-python-language-rules"></a>
107
+
108
+ <a id="python-language-rules"></a>
109
+ ## 2 Python Language Rules
110
+
111
+ <a id="s2.1-lint"></a>
112
+ <a id="21-lint"></a>
113
+
114
+ <a id="lint"></a>
115
+ ### 2.1 Lint
116
+
117
+ Run `pylint` over your code using this [pylintrc](https://google.github.io/styleguide/pylintrc).
118
+
119
+ <a id="s2.1.1-definition"></a>
120
+ <a id="211-definition"></a>
121
+
122
+ <a id="lint-definition"></a>
123
+ #### 2.1.1 Definition
124
+
125
+ `pylint`
126
+ is a tool for finding bugs and style problems in Python source code. It finds
127
+ problems that are typically caught by a compiler for less dynamic languages like
128
+ C and C++. Because of the dynamic nature of Python, some
129
+ warnings may be incorrect; however, spurious warnings should be fairly
130
+ infrequent.
131
+
132
+ <a id="s2.1.2-pros"></a>
133
+ <a id="212-pros"></a>
134
+
135
+ <a id="lint-pros"></a>
136
+ #### 2.1.2 Pros
137
+
138
+ Catches easy-to-miss errors like typos, using-vars-before-assignment, etc.
139
+
140
+ <a id="s2.1.3-cons"></a>
141
+ <a id="213-cons"></a>
142
+
143
+ <a id="lint-cons"></a>
144
+ #### 2.1.3 Cons
145
+
146
+ `pylint`
147
+ isn't perfect. To take advantage of it, sometimes we'll need to write around it,
148
+ suppress its warnings or fix it.
149
+
150
+ <a id="s2.1.4-decision"></a>
151
+ <a id="214-decision"></a>
152
+
153
+ <a id="lint-decision"></a>
154
+ #### 2.1.4 Decision
155
+
156
+ Make sure you run
157
+ `pylint`
158
+ on your code.
159
+
160
+
161
+ Suppress warnings if they are inappropriate so that other issues are not hidden.
162
+ To suppress warnings, you can set a line-level comment:
163
+
164
+ ```python
165
+ def do_PUT(self): # WSGI name, so pylint: disable=invalid-name
166
+ ...
167
+ ```
168
+
169
+ `pylint`
170
+ warnings are each identified by symbolic name (`empty-docstring`)
171
+ Google-specific warnings start with `g-`.
172
+
173
+ If the reason for the suppression is not clear from the symbolic name, add an
174
+ explanation.
175
+
176
+ Suppressing in this way has the advantage that we can easily search for
177
+ suppressions and revisit them.
178
+
179
+ You can get a list of
180
+ `pylint`
181
+ warnings by doing:
182
+
183
+ ```shell
184
+ pylint --list-msgs
185
+ ```
186
+
187
+ To get more information on a particular message, use:
188
+
189
+ ```shell
190
+ pylint --help-msg=invalid-name
191
+ ```
192
+
193
+ Prefer `pylint: disable` to the deprecated older form `pylint: disable-msg`.
194
+
195
+ Unused argument warnings can be suppressed by deleting the variables at the
196
+ beginning of the function. Always include a comment explaining why you are
197
+ deleting it. "Unused." is sufficient. For example:
198
+
199
+ ```python
200
+ def viking_cafe_order(spam: str, beans: str, eggs: str | None = None) -> str:
201
+ del beans, eggs # Unused by vikings.
202
+ return spam + spam + spam
203
+ ```
204
+
205
+ Other common forms of suppressing this warning include using '`_`' as the
206
+ identifier for the unused argument or prefixing the argument name with
207
+ '`unused_`', or assigning them to '`_`'. These forms are allowed but no longer
208
+ encouraged. These break callers that pass arguments by name and do not enforce
209
+ that the arguments are actually unused.
210
+
211
+ <a id="s2.2-imports"></a>
212
+ <a id="22-imports"></a>
213
+
214
+ <a id="imports"></a>
215
+ ### 2.2 Imports
216
+
217
+ Use `import` statements for packages and modules only, not for individual types,
218
+ classes, or functions.
219
+
220
+ <a id="s2.2.1-definition"></a>
221
+ <a id="221-definition"></a>
222
+
223
+ <a id="imports-definition"></a>
224
+ #### 2.2.1 Definition
225
+
226
+ Reusability mechanism for sharing code from one module to another.
227
+
228
+ <a id="s2.2.2-pros"></a>
229
+ <a id="222-pros"></a>
230
+
231
+ <a id="imports-pros"></a>
232
+ #### 2.2.2 Pros
233
+
234
+ The namespace management convention is simple. The source of each identifier is
235
+ indicated in a consistent way; `x.Obj` says that object `Obj` is defined in
236
+ module `x`.
237
+
238
+ <a id="s2.2.3-cons"></a>
239
+ <a id="223-cons"></a>
240
+
241
+ <a id="imports-cons"></a>
242
+ #### 2.2.3 Cons
243
+
244
+ Module names can still collide. Some module names are inconveniently long.
245
+
246
+ <a id="s2.2.4-decision"></a>
247
+ <a id="224-decision"></a>
248
+
249
+ <a id="imports-decision"></a>
250
+ #### 2.2.4 Decision
251
+
252
+ * Use `import x` for importing packages and modules.
253
+ * Use `from x import y` where `x` is the package prefix and `y` is the module
254
+ name with no prefix.
255
+ * Use `from x import y as z` in any of the following circumstances:
256
+ - Two modules named `y` are to be imported.
257
+ - `y` conflicts with a top-level name defined in the current module.
258
+ - `y` conflicts with a common parameter name that is part of the public
259
+ API (e.g., `features`).
260
+ - `y` is an inconveniently long name.
261
+ - `y` is too generic in the context of your code (e.g., `from
262
+ storage.file_system import options as fs_options`).
263
+ * Use `import y as z` only when `z` is a standard abbreviation (e.g., `import
264
+ numpy as np`).
265
+
266
+ For example the module `sound.effects.echo` may be imported as follows:
267
+
268
+ ```python
269
+ from sound.effects import echo
270
+ ...
271
+ echo.EchoFilter(input, output, delay=0.7, atten=4)
272
+ ```
273
+
274
+ Do not use relative names in imports. Even if the module is in the same package,
275
+ use the full package name. This helps prevent unintentionally importing a
276
+ package twice.
277
+
278
+ <a id="imports-exemptions"></a>
279
+ ##### 2.2.4.1 Exemptions
280
+
281
+ Exemptions from this rule:
282
+
283
+ * Symbols from the following modules are used to support static analysis and
284
+ type checking:
285
+ * [`typing` module](#typing-imports)
286
+ * [`collections.abc` module](#typing-imports)
287
+ * [`typing_extensions` module](https://github.com/python/typing_extensions/blob/main/README.md)
288
+ * Redirects from the
289
+ [six.moves module](https://six.readthedocs.io/#module-six.moves).
290
+
291
+ <a id="s2.3-packages"></a>
292
+ <a id="23-packages"></a>
293
+
294
+ <a id="packages"></a>
295
+ ### 2.3 Packages
296
+
297
+ Import each module using the full pathname location of the module.
298
+
299
+ <a id="s2.3.1-pros"></a>
300
+ <a id="231-pros"></a>
301
+
302
+ <a id="packages-pros"></a>
303
+ #### 2.3.1 Pros
304
+
305
+ Avoids conflicts in module names or incorrect imports due to the module search
306
+ path not being what the author expected. Makes it easier to find modules.
307
+
308
+ <a id="s2.3.2-cons"></a>
309
+ <a id="232-cons"></a>
310
+
311
+ <a id="packages-cons"></a>
312
+ #### 2.3.2 Cons
313
+
314
+ Makes it harder to deploy code because you have to replicate the package
315
+ hierarchy. Not really a problem with modern deployment mechanisms.
316
+
317
+ <a id="s2.3.3-decision"></a>
318
+ <a id="233-decision"></a>
319
+
320
+ <a id="packages-decision"></a>
321
+ #### 2.3.3 Decision
322
+
323
+ All new code should import each module by its full package name.
324
+
325
+ Imports should be as follows:
326
+
327
+ ```python
328
+ Yes:
329
+ # Reference absl.flags in code with the complete name (verbose).
330
+ import absl.flags
331
+ from doctor.who import jodie
332
+
333
+ _FOO = absl.flags.DEFINE_string(...)
334
+ ```
335
+
336
+ ```python
337
+ Yes:
338
+ # Reference flags in code with just the module name (common).
339
+ from absl import flags
340
+ from doctor.who import jodie
341
+
342
+ _FOO = flags.DEFINE_string(...)
343
+ ```
344
+
345
+ *(assume this file lives in `doctor/who/` where `jodie.py` also exists)*
346
+
347
+ ```python
348
+ No:
349
+ # Unclear what module the author wanted and what will be imported. The actual
350
+ # import behavior depends on external factors controlling sys.path.
351
+ # Which possible jodie module did the author intend to import?
352
+ import jodie
353
+ ```
354
+
355
+ The directory the main binary is located in should not be assumed to be in
356
+ `sys.path` despite that happening in some environments. This being the case,
357
+ code should assume that `import jodie` refers to a third-party or top-level
358
+ package named `jodie`, not a local `jodie.py`.
359
+
360
+
361
+ <a id="s2.4-exceptions"></a>
362
+ <a id="24-exceptions"></a>
363
+
364
+ <a id="exceptions"></a>
365
+ ### 2.4 Exceptions
366
+
367
+ Exceptions are allowed but must be used carefully.
368
+
369
+ <a id="s2.4.1-definition"></a>
370
+ <a id="241-definition"></a>
371
+
372
+ <a id="exceptions-definition"></a>
373
+ #### 2.4.1 Definition
374
+
375
+ Exceptions are a means of breaking out of normal control flow to handle errors
376
+ or other exceptional conditions.
377
+
378
+ <a id="s2.4.2-pros"></a>
379
+ <a id="242-pros"></a>
380
+
381
+ <a id="exceptions-pros"></a>
382
+ #### 2.4.2 Pros
383
+
384
+ The control flow of normal operation code is not cluttered by error-handling
385
+ code. It also allows the control flow to skip multiple frames when a certain
386
+ condition occurs, e.g., returning from N nested functions in one step instead of
387
+ having to plumb error codes through.
388
+
389
+ <a id="s2.4.3-cons"></a>
390
+ <a id="243-cons"></a>
391
+
392
+ <a id="exceptions-cons"></a>
393
+ #### 2.4.3 Cons
394
+
395
+ May cause the control flow to be confusing. Easy to miss error cases when making
396
+ library calls.
397
+
398
+ <a id="s2.4.4-decision"></a>
399
+ <a id="244-decision"></a>
400
+
401
+ <a id="exceptions-decision"></a>
402
+ #### 2.4.4 Decision
403
+
404
+ Exceptions must follow certain conditions:
405
+
406
+ - Make use of built-in exception classes when it makes sense. For example,
407
+ raise a `ValueError` to indicate a programming mistake like a violated
408
+ precondition, such as may happen when validating function arguments.
409
+
410
+ - Do not use `assert` statements in place of conditionals or validating
411
+ preconditions. They must not be critical to the application logic. A litmus
412
+ test would be that the `assert` could be removed without breaking the code.
413
+ `assert` conditionals are
414
+ [not guaranteed](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement)
415
+ to be evaluated. For [pytest](https://pytest.org) based tests, `assert` is
416
+ okay and expected to verify expectations. For
417
+ example:
418
+
419
+
420
+ ```python
421
+ Yes:
422
+ def connect_to_next_port(self, minimum: int) -> int:
423
+ """Connects to the next available port.
424
+
425
+ Args:
426
+ minimum: A port value greater or equal to 1024.
427
+
428
+ Returns:
429
+ The new minimum port.
430
+
431
+ Raises:
432
+ ConnectionError: If no available port is found.
433
+ """
434
+ if minimum < 1024:
435
+ # Note that this raising of ValueError is not mentioned in the doc
436
+ # string's "Raises:" section because it is not appropriate to
437
+ # guarantee this specific behavioral reaction to API misuse.
438
+ raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
439
+ port = self._find_next_open_port(minimum)
440
+ if port is None:
441
+ raise ConnectionError(
442
+ f'Could not connect to service on port {minimum} or higher.')
443
+ # The code does not depend on the result of this assert.
444
+ assert port >= minimum, (
445
+ f'Unexpected port {port} when minimum was {minimum}.')
446
+ return port
447
+ ```
448
+
449
+ ```python
450
+ No:
451
+ def connect_to_next_port(self, minimum: int) -> int:
452
+ """Connects to the next available port.
453
+
454
+ Args:
455
+ minimum: A port value greater or equal to 1024.
456
+
457
+ Returns:
458
+ The new minimum port.
459
+ """
460
+ assert minimum >= 1024, 'Minimum port must be at least 1024.'
461
+ # The following code depends on the previous assert.
462
+ port = self._find_next_open_port(minimum)
463
+ assert port is not None
464
+ # The type checking of the return statement relies on the assert.
465
+ return port
466
+ ```
467
+
468
+
469
+ - Libraries or packages may define their own exceptions. When doing so they
470
+ must inherit from an existing exception class. Exception names should end in
471
+ `Error` and should not introduce repetition (`foo.FooError`).
472
+
473
+ - Never use catch-all `except:` statements, or catch `Exception` or
474
+ `StandardError`, unless you are
475
+
476
+ - re-raising the exception, or
477
+ - creating an isolation point in the program where exceptions are not
478
+ propagated but are recorded and suppressed instead, such as protecting a
479
+ thread from crashing by guarding its outermost block.
480
+
481
+ Python is very tolerant in this regard and `except:` will really catch
482
+ everything including misspelled names, sys.exit() calls, Ctrl+C interrupts,
483
+ unittest failures and all kinds of other exceptions that you simply don't
484
+ want to catch.
485
+
486
+ - Minimize the amount of code in a `try`/`except` block. The larger the body
487
+ of the `try`, the more likely that an exception will be raised by a line of
488
+ code that you didn't expect to raise an exception. In those cases, the
489
+ `try`/`except` block hides a real error.
490
+
491
+ - Use the `finally` clause to execute code whether or not an exception is
492
+ raised in the `try` block. This is often useful for cleanup, i.e., closing a
493
+ file.
494
+
495
+ <a id="s2.5-global-variables"></a>
496
+ <a id="25-global-variables"></a>
497
+ <a id="s2.5-global-state"></a>
498
+ <a id="25-global-state"></a>
499
+
500
+ <a id="global-variables"></a>
501
+ ### 2.5 Mutable Global State
502
+
503
+ Avoid mutable global state.
504
+
505
+ <a id="s2.5.1-definition"></a>
506
+ <a id="251-definition"></a>
507
+
508
+ <a id="global-variables-definition"></a>
509
+ #### 2.5.1 Definition
510
+
511
+ Module-level values or class attributes that can get mutated during program
512
+ execution.
513
+
514
+ <a id="s2.5.2-pros"></a>
515
+ <a id="252-pros"></a>
516
+
517
+ <a id="global-variables-pros"></a>
518
+ #### 2.5.2 Pros
519
+
520
+ Occasionally useful.
521
+
522
+ <a id="s2.5.3-cons"></a>
523
+ <a id="253-cons"></a>
524
+
525
+ <a id="global-variables-cons"></a>
526
+ #### 2.5.3 Cons
527
+
528
+ * Breaks encapsulation: Such design can make it hard to achieve valid
529
+ objectives. For example, if global state is used to manage a database
530
+ connection, then connecting to two different databases at the same time
531
+ (such as for computing differences during a migration) becomes difficult.
532
+ Similar problems easily arise with global registries.
533
+
534
+ * Has the potential to change module behavior during the import, because
535
+ assignments to global variables are done when the module is first imported.
536
+
537
+ <a id="s2.5.4-decision"></a>
538
+ <a id="254-decision"></a>
539
+
540
+ <a id="global-variables-decision"></a>
541
+ #### 2.5.4 Decision
542
+
543
+ Avoid mutable global state.
544
+
545
+ In those rare cases where using global state is warranted, mutable global
546
+ entities should be declared at the module level or as a class attribute and made
547
+ internal by prepending an `_` to the name. If necessary, external access to
548
+ mutable global state must be done through public functions or class methods. See
549
+ [Naming](#s3.16-naming) below. Please explain the design reasons why mutable
550
+ global state is being used in a comment or a doc linked to from a comment.
551
+
552
+ Module-level constants are permitted and encouraged. For example:
553
+ `_MAX_HOLY_HANDGRENADE_COUNT = 3` for an internal use constant or
554
+ `SIR_LANCELOTS_FAVORITE_COLOR = "blue"` for a public API constant. Constants
555
+ must be named using all caps with underscores. See [Naming](#s3.16-naming)
556
+ below.
557
+
558
+ <a id="s2.6-nested"></a>
559
+ <a id="26-nested"></a>
560
+
561
+ <a id="nested-classes-functions"></a>
562
+ ### 2.6 Nested/Local/Inner Classes and Functions
563
+
564
+ Nested local functions or classes are fine when used to close over a local
565
+ variable. Inner classes are fine.
566
+
567
+ <a id="s2.6.1-definition"></a>
568
+ <a id="261-definition"></a>
569
+
570
+ <a id="nested-classes-functions-definition"></a>
571
+ #### 2.6.1 Definition
572
+
573
+ A class can be defined inside of a method, function, or class. A function can be
574
+ defined inside a method or function. Nested functions have read-only access to
575
+ variables defined in enclosing scopes.
576
+
577
+ <a id="s2.6.2-pros"></a>
578
+ <a id="262-pros"></a>
579
+
580
+ <a id="nested-classes-functions-pros"></a>
581
+ #### 2.6.2 Pros
582
+
583
+ Allows definition of utility classes and functions that are only used inside of
584
+ a very limited scope. Very
585
+ [ADT](https://en.wikipedia.org/wiki/Abstract_data_type)-y. Commonly used for
586
+ implementing decorators.
587
+
588
+ <a id="s2.6.3-cons"></a>
589
+ <a id="263-cons"></a>
590
+
591
+ <a id="nested-classes-functions-cons"></a>
592
+ #### 2.6.3 Cons
593
+
594
+ Nested functions and classes cannot be directly tested. Nesting can make the
595
+ outer function longer and less readable.
596
+
597
+ <a id="s2.6.4-decision"></a>
598
+ <a id="264-decision"></a>
599
+
600
+ <a id="nested-classes-functions-decision"></a>
601
+ #### 2.6.4 Decision
602
+
603
+ They are fine with some caveats. Avoid nested functions or classes except when
604
+ closing over a local value other than `self` or `cls`. Do not nest a function
605
+ just to hide it from users of a module. Instead, prefix its name with an \_ at
606
+ the module level so that it can still be accessed by tests.
607
+
608
+ <a id="s2.7-comprehensions"></a>
609
+ <a id="s2.7-list_comprehensions"></a>
610
+ <a id="27-list_comprehensions"></a>
611
+ <a id="list_comprehensions"></a>
612
+ <a id="list-comprehensions"></a>
613
+
614
+ <a id="comprehensions"></a>
615
+ ### 2.7 Comprehensions & Generator Expressions
616
+
617
+ Okay to use for simple cases.
618
+
619
+ <a id="s2.7.1-definition"></a>
620
+ <a id="271-definition"></a>
621
+
622
+ <a id="comprehensions-definition"></a>
623
+ #### 2.7.1 Definition
624
+
625
+ List, Dict, and Set comprehensions as well as generator expressions provide a
626
+ concise and efficient way to create container types and iterators without
627
+ resorting to the use of traditional loops, `map()`, `filter()`, or `lambda`.
628
+
629
+ <a id="s2.7.2-pros"></a>
630
+ <a id="272-pros"></a>
631
+
632
+ <a id="comprehensions-pros"></a>
633
+ #### 2.7.2 Pros
634
+
635
+ Simple comprehensions can be clearer and simpler than other dict, list, or set
636
+ creation techniques. Generator expressions can be very efficient, since they
637
+ avoid the creation of a list entirely.
638
+
639
+ <a id="s2.7.3-cons"></a>
640
+ <a id="273-cons"></a>
641
+
642
+ <a id="comprehensions-cons"></a>
643
+ #### 2.7.3 Cons
644
+
645
+ Complicated comprehensions or generator expressions can be hard to read.
646
+
647
+ <a id="s2.7.4-decision"></a>
648
+ <a id="274-decision"></a>
649
+
650
+ <a id="comprehensions-decision"></a>
651
+ #### 2.7.4 Decision
652
+
653
+ Comprehensions are allowed, however multiple `for` clauses or filter expressions
654
+ are not permitted. Optimize for readability, not conciseness.
655
+
656
+ ```python
657
+ Yes:
658
+ result = [mapping_expr for value in iterable if filter_expr]
659
+
660
+ result = [
661
+ is_valid(metric={'key': value})
662
+ for value in interesting_iterable
663
+ if a_longer_filter_expression(value)
664
+ ]
665
+
666
+ descriptive_name = [
667
+ transform({'key': key, 'value': value}, color='black')
668
+ for key, value in generate_iterable(some_input)
669
+ if complicated_condition_is_met(key, value)
670
+ ]
671
+
672
+ result = []
673
+ for x in range(10):
674
+ for y in range(5):
675
+ if x * y > 10:
676
+ result.append((x, y))
677
+
678
+ return {
679
+ x: complicated_transform(x)
680
+ for x in long_generator_function(parameter)
681
+ if x is not None
682
+ }
683
+
684
+ return (x**2 for x in range(10))
685
+
686
+ unique_names = {user.name for user in users if user is not None}
687
+ ```
688
+
689
+ ```python
690
+ No:
691
+ result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]
692
+
693
+ return (
694
+ (x, y, z)
695
+ for x in range(5)
696
+ for y in range(5)
697
+ if x != y
698
+ for z in range(5)
699
+ if y != z
700
+ )
701
+ ```
702
+
703
+ <a id="s2.8-default-iterators-and-operators"></a>
704
+
705
+ <a id="default-iterators-operators"></a>
706
+ ### 2.8 Default Iterators and Operators
707
+
708
+ Use default iterators and operators for types that support them, like lists,
709
+ dictionaries, and files.
710
+
711
+ <a id="s2.8.1-definition"></a>
712
+ <a id="281-definition"></a>
713
+
714
+ <a id="default-iterators-operators-definition"></a>
715
+ #### 2.8.1 Definition
716
+
717
+ Container types, like dictionaries and lists, define default iterators and
718
+ membership test operators ("in" and "not in").
719
+
720
+ <a id="s2.8.2-pros"></a>
721
+ <a id="282-pros"></a>
722
+
723
+ <a id="default-iterators-operators-pros"></a>
724
+ #### 2.8.2 Pros
725
+
726
+ The default iterators and operators are simple and efficient. They express the
727
+ operation directly, without extra method calls. A function that uses default
728
+ operators is generic. It can be used with any type that supports the operation.
729
+
730
+ <a id="s2.8.3-cons"></a>
731
+ <a id="283-cons"></a>
732
+
733
+ <a id="default-iterators-operators-cons"></a>
734
+ #### 2.8.3 Cons
735
+
736
+ You can't tell the type of objects by reading the method names (unless the
737
+ variable has type annotations). This is also an advantage.
738
+
739
+ <a id="s2.8.4-decision"></a>
740
+ <a id="284-decision"></a>
741
+
742
+ <a id="default-iterators-operators-decision"></a>
743
+ #### 2.8.4 Decision
744
+
745
+ Use default iterators and operators for types that support them, like lists,
746
+ dictionaries, and files. The built-in types define iterator methods, too. Prefer
747
+ these methods to methods that return lists, except that you should not mutate a
748
+ container while iterating over it.
749
+
750
+ ```python
751
+ Yes: for key in adict: ...
752
+ if obj in alist: ...
753
+ for line in afile: ...
754
+ for k, v in adict.items(): ...
755
+ ```
756
+
757
+ ```python
758
+ No: for key in adict.keys(): ...
759
+ for line in afile.readlines(): ...
760
+ ```
761
+
762
+ <a id="s2.9-generators"></a>
763
+ <a id="29-generators"></a>
764
+
765
+ <a id="generators"></a>
766
+ ### 2.9 Generators
767
+
768
+ Use generators as needed.
769
+
770
+ <a id="s2.9.1-definition"></a>
771
+ <a id="291-definition"></a>
772
+
773
+ <a id="generators-definition"></a>
774
+ #### 2.9.1 Definition
775
+
776
+ A generator function returns an iterator that yields a value each time it
777
+ executes a yield statement. After it yields a value, the runtime state of the
778
+ generator function is suspended until the next value is needed.
779
+
780
+ <a id="s2.9.2-pros"></a>
781
+ <a id="292-pros"></a>
782
+
783
+ <a id="generators-pros"></a>
784
+ #### 2.9.2 Pros
785
+
786
+ Simpler code, because the state of local variables and control flow are
787
+ preserved for each call. A generator uses less memory than a function that
788
+ creates an entire list of values at once.
789
+
790
+ <a id="s2.9.3-cons"></a>
791
+ <a id="293-cons"></a>
792
+
793
+ <a id="generators-cons"></a>
794
+ #### 2.9.3 Cons
795
+
796
+ Local variables in the generator will not be garbage collected until the
797
+ generator is either consumed to exhaustion or itself garbage collected.
798
+
799
+ <a id="s2.9.4-decision"></a>
800
+ <a id="294-decision"></a>
801
+
802
+ <a id="generators-decision"></a>
803
+ #### 2.9.4 Decision
804
+
805
+ Fine. Use "Yields:" rather than "Returns:" in the docstring for generator
806
+ functions.
807
+
808
+ If the generator manages an expensive resource, make sure to force the clean up.
809
+
810
+ A good way to do the clean up is by wrapping the generator with a context
811
+ manager [PEP-0533](https://peps.python.org/pep-0533/).
812
+
813
+ <a id="s2.10-lambda-functions"></a>
814
+ <a id="210-lambda-functions"></a>
815
+
816
+ <a id="lambdas"></a>
817
+ ### 2.10 Lambda Functions
818
+
819
+ Okay for one-liners. Prefer generator expressions over `map()` or `filter()`
820
+ with a `lambda`.
821
+
822
+ <a id="s2.10.1-definition"></a>
823
+ <a id="2101-definition"></a>
824
+
825
+ <a id="lambdas-definition"></a>
826
+ #### 2.10.1 Definition
827
+
828
+ Lambdas define anonymous functions in an expression, as opposed to a statement.
829
+
830
+ <a id="s2.10.2-pros"></a>
831
+ <a id="2102-pros"></a>
832
+
833
+ <a id="lambdas-pros"></a>
834
+ #### 2.10.2 Pros
835
+
836
+ Convenient.
837
+
838
+ <a id="s2.10.3-cons"></a>
839
+ <a id="2103-cons"></a>
840
+
841
+ <a id="lambdas-cons"></a>
842
+ #### 2.10.3 Cons
843
+
844
+ Harder to read and debug than local functions. The lack of names means stack
845
+ traces are more difficult to understand. Expressiveness is limited because the
846
+ function may only contain an expression.
847
+
848
+ <a id="s2.10.4-decision"></a>
849
+ <a id="2104-decision"></a>
850
+
851
+ <a id="lambdas-decision"></a>
852
+ #### 2.10.4 Decision
853
+
854
+ Lambdas are allowed. If the code inside the lambda function spans multiple lines
855
+ or is longer than 60-80 chars, it might be better to define it as a regular
856
+ [nested function](#lexical-scoping).
857
+
858
+ For common operations like multiplication, use the functions from the `operator`
859
+ module instead of lambda functions. For example, prefer `operator.mul` to
860
+ `lambda x, y: x * y`.
861
+
862
+ <a id="s2.11-conditional-expressions"></a>
863
+ <a id="211-conditional-expressions"></a>
864
+
865
+ <a id="conditional-expressions"></a>
866
+ ### 2.11 Conditional Expressions
867
+
868
+ Okay for simple cases.
869
+
870
+ <a id="s2.11.1-definition"></a>
871
+ <a id="2111-definition"></a>
872
+
873
+ <a id="conditional-expressions-definition"></a>
874
+ #### 2.11.1 Definition
875
+
876
+ Conditional expressions (sometimes called a “ternary operator”) are mechanisms
877
+ that provide a shorter syntax for if statements. For example: `x = 1 if cond
878
+ else 2`.
879
+
880
+ <a id="s2.11.2-pros"></a>
881
+ <a id="2112-pros"></a>
882
+
883
+ <a id="conditional-expressions-pros"></a>
884
+ #### 2.11.2 Pros
885
+
886
+ Shorter and more convenient than an if statement.
887
+
888
+ <a id="s2.11.3-cons"></a>
889
+ <a id="2113-cons"></a>
890
+
891
+ <a id="conditional-expressions-cons"></a>
892
+ #### 2.11.3 Cons
893
+
894
+ May be harder to read than an if statement. The condition may be difficult to
895
+ locate if the expression is long.
896
+
897
+ <a id="s2.11.4-decision"></a>
898
+ <a id="2114-decision"></a>
899
+
900
+ <a id="conditional-expressions-decision"></a>
901
+ #### 2.11.4 Decision
902
+
903
+ Okay to use for simple cases. Each portion must fit on one line:
904
+ true-expression, if-expression, else-expression. Use a complete if statement
905
+ when things get more complicated.
906
+
907
+ ```python
908
+ Yes:
909
+ one_line = 'yes' if predicate(value) else 'no'
910
+ slightly_split = ('yes' if predicate(value)
911
+ else 'no, nein, nyet')
912
+ the_longest_ternary_style_that_can_be_done = (
913
+ 'yes, true, affirmative, confirmed, correct'
914
+ if predicate(value)
915
+ else 'no, false, negative, nay')
916
+ ```
917
+
918
+ ```python
919
+ No:
920
+ bad_line_breaking = ('yes' if predicate(value) else
921
+ 'no')
922
+ portion_too_long = ('yes'
923
+ if some_long_module.some_long_predicate_function(
924
+ really_long_variable_name)
925
+ else 'no, false, negative, nay')
926
+ ```
927
+
928
+ <a id="s2.12-default-argument-values"></a>
929
+ <a id="212-default-argument-values"></a>
930
+
931
+ <a id="default-arguments"></a>
932
+ ### 2.12 Default Argument Values
933
+
934
+ Okay in most cases.
935
+
936
+ <a id="s2.12.1-definition"></a>
937
+ <a id="2121-definition"></a>
938
+
939
+ <a id="default-arguments-definition"></a>
940
+ #### 2.12.1 Definition
941
+
942
+ You can specify values for variables at the end of a function's parameter list,
943
+ e.g., `def foo(a, b=0):`. If `foo` is called with only one argument, `b` is set
944
+ to 0. If it is called with two arguments, `b` has the value of the second
945
+ argument.
946
+
947
+ <a id="s2.12.2-pros"></a>
948
+ <a id="2122-pros"></a>
949
+
950
+ <a id="default-arguments-pros"></a>
951
+ #### 2.12.2 Pros
952
+
953
+ Often you have a function that uses lots of default values, but on rare
954
+ occasions you want to override the defaults. Default argument values provide an
955
+ easy way to do this, without having to define lots of functions for the rare
956
+ exceptions. As Python does not support overloaded methods/functions, default
957
+ arguments are an easy way of "faking" the overloading behavior.
958
+
959
+ <a id="s2.12.3-cons"></a>
960
+ <a id="2123-cons"></a>
961
+
962
+ <a id="default-arguments-cons"></a>
963
+ #### 2.12.3 Cons
964
+
965
+ Default arguments are evaluated once at module load time. This may cause
966
+ problems if the argument is a mutable object such as a list or a dictionary. If
967
+ the function modifies the object (e.g., by appending an item to a list), the
968
+ default value is modified.
969
+
970
+ <a id="s2.12.4-decision"></a>
971
+ <a id="2124-decision"></a>
972
+
973
+ <a id="default-arguments-decision"></a>
974
+ #### 2.12.4 Decision
975
+
976
+ Okay to use with the following caveat:
977
+
978
+ Do not use mutable objects as default values in the function or method
979
+ definition.
980
+
981
+ ```python
982
+ Yes: def foo(a, b=None):
983
+ if b is None:
984
+ b = []
985
+ Yes: def foo(a, b: Sequence | None = None):
986
+ if b is None:
987
+ b = []
988
+ Yes: def foo(a, b: Sequence = ()): # Empty tuple OK since tuples are immutable.
989
+ ...
990
+ ```
991
+
992
+ ```python
993
+ from absl import flags
994
+ _FOO = flags.DEFINE_string(...)
995
+
996
+ No: def foo(a, b=[]):
997
+ ...
998
+ No: def foo(a, b=time.time()): # Is `b` supposed to represent when this module was loaded?
999
+ ...
1000
+ No: def foo(a, b=_FOO.value): # sys.argv has not yet been parsed...
1001
+ ...
1002
+ No: def foo(a, b: Mapping = {}): # Could still get passed to unchecked code.
1003
+ ...
1004
+ ```
1005
+
1006
+ <a id="s2.13-properties"></a>
1007
+ <a id="213-properties"></a>
1008
+
1009
+ <a id="properties"></a>
1010
+ ### 2.13 Properties
1011
+
1012
+ Properties may be used to control getting or setting attributes that require
1013
+ trivial computations or logic. Property implementations must match the general
1014
+ expectations of regular attribute access: that they are cheap, straightforward,
1015
+ and unsurprising.
1016
+
1017
+ <a id="s2.13.1-definition"></a>
1018
+ <a id="2131-definition"></a>
1019
+
1020
+ <a id="properties-definition"></a>
1021
+ #### 2.13.1 Definition
1022
+
1023
+ A way to wrap method calls for getting and setting an attribute as a standard
1024
+ attribute access.
1025
+
1026
+ <a id="s2.13.2-pros"></a>
1027
+ <a id="2132-pros"></a>
1028
+
1029
+ <a id="properties-pros"></a>
1030
+ #### 2.13.2 Pros
1031
+
1032
+ * Allows for an attribute access and assignment API rather than
1033
+ [getter and setter](#getters-and-setters) method calls.
1034
+ * Can be used to make an attribute read-only.
1035
+ * Allows calculations to be lazy.
1036
+ * Provides a way to maintain the public interface of a class when the
1037
+ internals evolve independently of class users.
1038
+
1039
+ <a id="s2.13.3-cons"></a>
1040
+ <a id="2133-cons"></a>
1041
+
1042
+ <a id="properties-cons"></a>
1043
+ #### 2.13.3 Cons
1044
+
1045
+ * Can hide side-effects much like operator overloading.
1046
+ * Can be confusing for subclasses.
1047
+
1048
+ <a id="s2.13.4-decision"></a>
1049
+ <a id="2134-decision"></a>
1050
+
1051
+ <a id="properties-decision"></a>
1052
+ #### 2.13.4 Decision
1053
+
1054
+ Properties are allowed, but, like operator overloading, should only be used when
1055
+ necessary and match the expectations of typical attribute access; follow the
1056
+ [getters and setters](#getters-and-setters) rules otherwise.
1057
+
1058
+ For example, using a property to simply both get and set an internal attribute
1059
+ isn't allowed: there is no computation occurring, so the property is unnecessary
1060
+ ([make the attribute public instead](#getters-and-setters)). In comparison,
1061
+ using a property to control attribute access or to calculate a *trivially*
1062
+ derived value is allowed: the logic is simple and unsurprising.
1063
+
1064
+ Properties should be created with the `@property`
1065
+ [decorator](#s2.17-function-and-method-decorators). Manually implementing a
1066
+ property descriptor is considered a [power feature](#power-features).
1067
+
1068
+ Inheritance with properties can be non-obvious. Do not use properties to
1069
+ implement computations a subclass may ever want to override and extend.
1070
+
1071
+ <a id="s2.14-truefalse-evaluations"></a>
1072
+ <a id="214-truefalse-evaluations"></a>
1073
+
1074
+ <a id="truefalse-evaluations"></a>
1075
+ ### 2.14 True/False Evaluations
1076
+
1077
+ Use the "implicit" false if at all possible (with a few caveats).
1078
+
1079
+ <a id="s2.14.1-definition"></a>
1080
+ <a id="2141-definition"></a>
1081
+
1082
+ <a id="truefalse-evaluations-definition"></a>
1083
+ #### 2.14.1 Definition
1084
+
1085
+ Python evaluates certain values as `False` when in a boolean context. A quick
1086
+ "rule of thumb" is that all "empty" values are considered false, so `0, None,
1087
+ [], {}, ''` all evaluate as false in a boolean context.
1088
+
1089
+ <a id="s2.14.2-pros"></a>
1090
+ <a id="2142-pros"></a>
1091
+
1092
+ <a id="truefalse-evaluations-pros"></a>
1093
+ #### 2.14.2 Pros
1094
+
1095
+ Conditions using Python booleans are easier to read and less error-prone. In
1096
+ most cases, they're also faster.
1097
+
1098
+ <a id="s2.14.3-cons"></a>
1099
+ <a id="2143-cons"></a>
1100
+
1101
+ <a id="truefalse-evaluations-cons"></a>
1102
+ #### 2.14.3 Cons
1103
+
1104
+ May look strange to C/C++ developers.
1105
+
1106
+ <a id="s2.14.4-decision"></a>
1107
+ <a id="2144-decision"></a>
1108
+
1109
+ <a id="truefalse-evaluations-decision"></a>
1110
+ #### 2.14.4 Decision
1111
+
1112
+ Use the "implicit" false if possible, e.g., `if foo:` rather than `if foo !=
1113
+ []:`. There are a few caveats that you should keep in mind though:
1114
+
1115
+ - Always use `if foo is None:` (or `is not None`) to check for a `None` value.
1116
+ E.g., when testing whether a variable or argument that defaults to `None`
1117
+ was set to some other value. The other value might be a value that's false
1118
+ in a boolean context!
1119
+
1120
+ - Never compare a boolean variable to `False` using `==`. Use `if not x:`
1121
+ instead. If you need to distinguish `False` from `None` then chain the
1122
+ expressions, such as `if not x and x is not None:`.
1123
+
1124
+ - For sequences (strings, lists, tuples), use the fact that empty sequences
1125
+ are false, so `if seq:` and `if not seq:` are preferable to `if len(seq):`
1126
+ and `if not len(seq):` respectively.
1127
+
1128
+ - When handling integers, implicit false may involve more risk than benefit
1129
+ (i.e., accidentally handling `None` as 0). You may compare a value which is
1130
+ known to be an integer (and is not the result of `len()`) against the
1131
+ integer 0.
1132
+
1133
+ ```python
1134
+ Yes: if not users:
1135
+ print('no users')
1136
+
1137
+ if i % 10 == 0:
1138
+ self.handle_multiple_of_ten()
1139
+
1140
+ def f(x=None):
1141
+ if x is None:
1142
+ x = []
1143
+ ```
1144
+
1145
+ ```python
1146
+ No: if len(users) == 0:
1147
+ print('no users')
1148
+
1149
+ if not i % 10:
1150
+ self.handle_multiple_of_ten()
1151
+
1152
+ def f(x=None):
1153
+ x = x or []
1154
+ ```
1155
+
1156
+ - Note that `'0'` (i.e., `0` as string) evaluates to true.
1157
+
1158
+ - Note that Numpy arrays may raise an exception in an implicit boolean
1159
+ context. Prefer the `.size` attribute when testing emptiness of a `np.array`
1160
+ (e.g. `if not users.size`).
1161
+
1162
+ <a id="s2.16-lexical-scoping"></a>
1163
+ <a id="216-lexical-scoping"></a>
1164
+
1165
+ <a id="lexical-scoping"></a>
1166
+ ### 2.16 Lexical Scoping
1167
+
1168
+ Okay to use.
1169
+
1170
+ <a id="s2.16.1-definition"></a>
1171
+ <a id="2161-definition"></a>
1172
+
1173
+ <a id="lexical-scoping-definition"></a>
1174
+ #### 2.16.1 Definition
1175
+
1176
+ A nested Python function can refer to variables defined in enclosing functions,
1177
+ but cannot assign to them. Variable bindings are resolved using lexical scoping,
1178
+ that is, based on the static program text. Any assignment to a name in a block
1179
+ will cause Python to treat all references to that name as a local variable, even
1180
+ if the use precedes the assignment. If a global declaration occurs, the name is
1181
+ treated as a global variable.
1182
+
1183
+ An example of the use of this feature is:
1184
+
1185
+ ```python
1186
+ def get_adder(summand1: float) -> Callable[[float], float]:
1187
+ """Returns a function that adds numbers to a given number."""
1188
+ def adder(summand2: float) -> float:
1189
+ return summand1 + summand2
1190
+
1191
+ return adder
1192
+ ```
1193
+
1194
+ <a id="s2.16.2-pros"></a>
1195
+ <a id="2162-pros"></a>
1196
+
1197
+ <a id="lexical-scoping-pros"></a>
1198
+ #### 2.16.2 Pros
1199
+
1200
+ Often results in clearer, more elegant code. Especially comforting to
1201
+ experienced Lisp and Scheme (and Haskell and ML and ...) programmers.
1202
+
1203
+ <a id="s2.16.3-cons"></a>
1204
+ <a id="2163-cons"></a>
1205
+
1206
+ <a id="lexical-scoping-cons"></a>
1207
+ #### 2.16.3 Cons
1208
+
1209
+ Can lead to confusing bugs, such as this example based on
1210
+ [PEP-0227](https://peps.python.org/pep-0227/):
1211
+
1212
+ ```python
1213
+ i = 4
1214
+ def foo(x: Iterable[int]):
1215
+ def bar():
1216
+ print(i, end='')
1217
+ # ...
1218
+ # A bunch of code here
1219
+ # ...
1220
+ for i in x: # Ah, i *is* local to foo, so this is what bar sees
1221
+ print(i, end='')
1222
+ bar()
1223
+ ```
1224
+
1225
+ So `foo([1, 2, 3])` will print `1 2 3 3`,
1226
+ not `1 2 3 4`.
1227
+
1228
+ <a id="s2.16.4-decision"></a>
1229
+ <a id="2164-decision"></a>
1230
+
1231
+ <a id="lexical-scoping-decision"></a>
1232
+ #### 2.16.4 Decision
1233
+
1234
+ Okay to use.
1235
+
1236
+ <a id="s2.17-function-and-method-decorators"></a>
1237
+ <a id="217-function-and-method-decorators"></a>
1238
+ <a id="function-and-method-decorators"></a>
1239
+
1240
+ <a id="decorators"></a>
1241
+ ### 2.17 Function and Method Decorators
1242
+
1243
+ Use decorators judiciously when there is a clear advantage. Avoid `staticmethod`
1244
+ and limit use of `classmethod`.
1245
+
1246
+ <a id="s2.17.1-definition"></a>
1247
+ <a id="2171-definition"></a>
1248
+
1249
+ <a id="decorators-definition"></a>
1250
+ #### 2.17.1 Definition
1251
+
1252
+ [Decorators for Functions and Methods](https://docs.python.org/3/glossary.html#term-decorator)
1253
+ (a.k.a "the `@` notation"). One common decorator is `@property`, used for
1254
+ converting ordinary methods into dynamically computed attributes. However, the
1255
+ decorator syntax allows for user-defined decorators as well. Specifically, for
1256
+ some function `my_decorator`, this:
1257
+
1258
+ ```python
1259
+ class C:
1260
+ @my_decorator
1261
+ def method(self):
1262
+ # method body ...
1263
+ ```
1264
+
1265
+ is equivalent to:
1266
+
1267
+ ```python
1268
+ class C:
1269
+ def method(self):
1270
+ # method body ...
1271
+ method = my_decorator(method)
1272
+ ```
1273
+
1274
+ <a id="s2.17.2-pros"></a>
1275
+ <a id="2172-pros"></a>
1276
+
1277
+ <a id="decorators-pros"></a>
1278
+ #### 2.17.2 Pros
1279
+
1280
+ Elegantly specifies some transformation on a method; the transformation might
1281
+ eliminate some repetitive code, enforce invariants, etc.
1282
+
1283
+ <a id="s2.17.3-cons"></a>
1284
+ <a id="2173-cons"></a>
1285
+
1286
+ <a id="decorators-cons"></a>
1287
+ #### 2.17.3 Cons
1288
+
1289
+ Decorators can perform arbitrary operations on a function's arguments or return
1290
+ values, resulting in surprising implicit behavior. Additionally, decorators
1291
+ execute at object definition time. For module-level objects (classes, module
1292
+ functions, ...) this happens at import time. Failures in decorator code are
1293
+ pretty much impossible to recover from.
1294
+
1295
+ <a id="s2.17.4-decision"></a>
1296
+ <a id="2174-decision"></a>
1297
+
1298
+ <a id="decorators-decision"></a>
1299
+ #### 2.17.4 Decision
1300
+
1301
+ Use decorators judiciously when there is a clear advantage. Decorators should
1302
+ follow the same import and naming guidelines as functions. A decorator docstring
1303
+ should clearly state that the function is a decorator. Write unit tests for
1304
+ decorators.
1305
+
1306
+ Avoid external dependencies in the decorator itself (e.g. don't rely on files,
1307
+ sockets, database connections, etc.), since they might not be available when the
1308
+ decorator runs (at import time, perhaps from `pydoc` or other tools). A
1309
+ decorator that is called with valid parameters should (as much as possible) be
1310
+ guaranteed to succeed in all cases.
1311
+
1312
+ Decorators are a special case of "top-level code" - see [main](#s3.17-main) for
1313
+ more discussion.
1314
+
1315
+ Never use `staticmethod` unless forced to in order to integrate with an API
1316
+ defined in an existing library. Write a module-level function instead.
1317
+
1318
+ Use `classmethod` only when writing a named constructor, or a class-specific
1319
+ routine that modifies necessary global state such as a process-wide cache.
1320
+
1321
+ <a id="s2.18-threading"></a>
1322
+ <a id="218-threading"></a>
1323
+
1324
+ <a id="threading"></a>
1325
+ ### 2.18 Threading
1326
+
1327
+ Do not rely on the atomicity of built-in types.
1328
+
1329
+ While Python's built-in data types such as dictionaries appear to have atomic
1330
+ operations, there are corner cases where they aren't atomic (e.g. if `__hash__`
1331
+ or `__eq__` are implemented as Python methods) and their atomicity should not be
1332
+ relied upon. Neither should you rely on atomic variable assignment (since this
1333
+ in turn depends on dictionaries).
1334
+
1335
+ Use the `queue` module's `Queue` data type as the preferred way to communicate
1336
+ data between threads. Otherwise, use the `threading` module and its locking
1337
+ primitives. Prefer condition variables and `threading.Condition` instead of
1338
+ using lower-level locks.
1339
+
1340
+ <a id="s2.19-power-features"></a>
1341
+ <a id="219-power-features"></a>
1342
+
1343
+ <a id="power-features"></a>
1344
+ ### 2.19 Power Features
1345
+
1346
+ Avoid these features.
1347
+
1348
+ <a id="s2.19.1-definition"></a>
1349
+ <a id="2191-definition"></a>
1350
+
1351
+ <a id="power-features-definition"></a>
1352
+ #### 2.19.1 Definition
1353
+
1354
+ Python is an extremely flexible language and gives you many fancy features such
1355
+ as custom metaclasses, access to bytecode, on-the-fly compilation, dynamic
1356
+ inheritance, object reparenting, import hacks, reflection (e.g. some uses of
1357
+ `getattr()`), modification of system internals, `__del__` methods implementing
1358
+ customized cleanup, etc.
1359
+
1360
+ <a id="s2.19.2-pros"></a>
1361
+ <a id="2192-pros"></a>
1362
+
1363
+ <a id="power-features-pros"></a>
1364
+ #### 2.19.2 Pros
1365
+
1366
+ These are powerful language features. They can make your code more compact.
1367
+
1368
+ <a id="s2.19.3-cons"></a>
1369
+ <a id="2193-cons"></a>
1370
+
1371
+ <a id="power-features-cons"></a>
1372
+ #### 2.19.3 Cons
1373
+
1374
+ It's very tempting to use these "cool" features when they're not absolutely
1375
+ necessary. It's harder to read, understand, and debug code that's using unusual
1376
+ features underneath. It doesn't seem that way at first (to the original author),
1377
+ but when revisiting the code, it tends to be more difficult than code that is
1378
+ longer but is straightforward.
1379
+
1380
+ <a id="s2.19.4-decision"></a>
1381
+ <a id="2194-decision"></a>
1382
+
1383
+ <a id="power-features-decision"></a>
1384
+ #### 2.19.4 Decision
1385
+
1386
+ Avoid these features in your code.
1387
+
1388
+ Standard library modules and classes that internally use these features are okay
1389
+ to use (for example, `abc.ABCMeta`, `dataclasses`, and `enum`).
1390
+
1391
+ <a id="s2.20-modern-python"></a>
1392
+ <a id="220-modern-python"></a>
1393
+
1394
+ <a id="modern-python"></a>
1395
+ ### 2.20 Modern Python: from \_\_future\_\_ imports
1396
+
1397
+ New language version semantic changes may be gated behind a special future
1398
+ import to enable them on a per-file basis within earlier runtimes.
1399
+
1400
+ <a id="s2.20.1-definition"></a>
1401
+ <a id="2201-definition"></a>
1402
+
1403
+ <a id="modern-python-definition"></a>
1404
+ #### 2.20.1 Definition
1405
+
1406
+ Being able to turn on some of the more modern features via `from __future__
1407
+ import` statements allows early use of features from expected future Python
1408
+ versions.
1409
+
1410
+ <a id="s2.20.2-pros"></a>
1411
+ <a id="2202-pros"></a>
1412
+
1413
+ <a id="modern-python-pros"></a>
1414
+ #### 2.20.2 Pros
1415
+
1416
+ This has proven to make runtime version upgrades smoother as changes can be made
1417
+ on a per-file basis while declaring compatibility and preventing regressions
1418
+ within those files. Modern code is more maintainable as it is less likely to
1419
+ accumulate technical debt that will be problematic during future runtime
1420
+ upgrades.
1421
+
1422
+ <a id="s2.20.3-cons"></a>
1423
+ <a id="2203-cons"></a>
1424
+
1425
+ <a id="modern-python-cons"></a>
1426
+ #### 2.20.3 Cons
1427
+
1428
+ Such code may not work on very old interpreter versions prior to the
1429
+ introduction of the needed future statement. The need for this is more common in
1430
+ projects supporting an extremely wide variety of environments.
1431
+
1432
+ <a id="s2.20.4-decision"></a>
1433
+ <a id="2204-decision"></a>
1434
+
1435
+ <a id="modern-python-decision"></a>
1436
+ #### 2.20.4 Decision
1437
+
1438
+ ##### from \_\_future\_\_ imports
1439
+
1440
+ Use of `from __future__ import` statements is encouraged. It allows a given
1441
+ source file to start using more modern Python syntax features today. Once you no
1442
+ longer need to run on a version where the features are hidden behind a
1443
+ `__future__` import, feel free to remove those lines.
1444
+
1445
+ In code that may execute on versions as old as 3.5 rather than >= 3.7, import:
1446
+
1447
+ ```python
1448
+ from __future__ import generator_stop
1449
+ ```
1450
+
1451
+ For more information read the
1452
+ [Python future statement definitions](https://docs.python.org/3/library/__future__.html)
1453
+ documentation.
1454
+
1455
+ Please don't remove these imports until you are confident the code is only ever
1456
+ used in a sufficiently modern environment. Even if you do not currently use the
1457
+ feature a specific future import enables in your code today, keeping it in place
1458
+ in the file prevents later modifications of the code from inadvertently
1459
+ depending on the older behavior.
1460
+
1461
+ Use other `from __future__` import statements as you see fit.
1462
+
1463
+ <a id="s2.21-type-annotated-code"></a>
1464
+ <a id="s2.21-typed-code"></a>
1465
+ <a id="221-type-annotated-code"></a>
1466
+ <a id="typed-code"></a>
1467
+
1468
+ <a id="typed-code"></a>
1469
+ ### 2.21 Type Annotated Code
1470
+
1471
+ You can annotate Python code with
1472
+ [type hints](https://docs.python.org/3/library/typing.html). Type-check the code
1473
+ at build time with a type checking tool like [pytype](https://github.com/google/pytype).
1474
+ In most cases, when feasible, type annotations are in source files. For
1475
+ third-party or extension modules, annotations can be in
1476
+ [stub `.pyi` files](https://peps.python.org/pep-0484/#stub-files).
1477
+
1478
+
1479
+ <a id="s2.21.1-definition"></a>
1480
+ <a id="2211-definition"></a>
1481
+
1482
+ <a id="typed-code-definition"></a>
1483
+ #### 2.21.1 Definition
1484
+
1485
+ Type annotations (or "type hints") are for function or method arguments and
1486
+ return values:
1487
+
1488
+ ```python
1489
+ def func(a: int) -> list[int]:
1490
+ ```
1491
+
1492
+ You can also declare the type of a variable using similar syntax:
1493
+
1494
+ ```python
1495
+ a: SomeType = some_func()
1496
+ ```
1497
+
1498
+ <a id="s2.21.2-pros"></a>
1499
+ <a id="2212-pros"></a>
1500
+
1501
+ <a id="typed-code-pros"></a>
1502
+ #### 2.21.2 Pros
1503
+
1504
+ Type annotations improve the readability and maintainability of your code. The
1505
+ type checker will convert many runtime errors to build-time errors, and reduce
1506
+ your ability to use [Power Features](#power-features).
1507
+
1508
+ <a id="s2.21.3-cons"></a>
1509
+ <a id="2213-cons"></a>
1510
+
1511
+ <a id="typed-code-cons"></a>
1512
+ #### 2.21.3 Cons
1513
+
1514
+ You will have to keep the type declarations up to date.
1515
+ You might see type errors that you think are
1516
+ valid code. Use of a
1517
+ [type checker](https://github.com/google/pytype)
1518
+ may reduce your ability to use [Power Features](#power-features).
1519
+
1520
+ <a id="s2.21.4-decision"></a>
1521
+ <a id="2214-decision"></a>
1522
+
1523
+ <a id="typed-code-decision"></a>
1524
+ #### 2.21.4 Decision
1525
+
1526
+ You are strongly encouraged to enable Python type analysis when updating code.
1527
+ When adding or modifying public APIs, include type annotations and enable
1528
+ checking via pytype in the build system. As static analysis is relatively new to
1529
+ Python, we acknowledge that undesired side-effects (such as
1530
+ wrongly
1531
+ inferred types) may prevent adoption by some projects. In those situations,
1532
+ authors are encouraged to add a comment with a TODO or link to a bug describing
1533
+ the issue(s) currently preventing type annotation adoption in the BUILD file or
1534
+ in the code itself as appropriate.
1535
+
1536
+ <a id="s3-python-style-rules"></a>
1537
+ <a id="3-python-style-rules"></a>
1538
+
1539
+ <a id="python-style-rules"></a>
1540
+ ## 3 Python Style Rules
1541
+
1542
+ <a id="s3.1-semicolons"></a>
1543
+ <a id="31-semicolons"></a>
1544
+
1545
+ <a id="semicolons"></a>
1546
+ ### 3.1 Semicolons
1547
+
1548
+ Do not terminate your lines with semicolons, and do not use semicolons to put
1549
+ two statements on the same line.
1550
+
1551
+ <a id="s3.2-line-length"></a>
1552
+ <a id="32-line-length"></a>
1553
+
1554
+ <a id="line-length"></a>
1555
+ ### 3.2 Line length
1556
+
1557
+ Maximum line length is *80 characters*.
1558
+
1559
+ Explicit exceptions to the 80 character limit:
1560
+
1561
+ - Long import statements.
1562
+ - URLs, pathnames, or long flags in comments.
1563
+ - Long string module-level constants not containing whitespace that would be
1564
+ inconvenient to split across lines such as URLs or pathnames.
1565
+ - Pylint disable comments. (e.g.: `# pylint: disable=invalid-name`)
1566
+
1567
+ Do not use a backslash for
1568
+ [explicit line continuation](https://docs.python.org/3/reference/lexical_analysis.html#explicit-line-joining).
1569
+
1570
+ Instead, make use of Python's
1571
+ [implicit line joining inside parentheses, brackets and braces](http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining).
1572
+ If necessary, you can add an extra pair of parentheses around an expression.
1573
+
1574
+ Note that this rule doesn't prohibit backslash-escaped newlines within strings
1575
+ (see [below](#strings)).
1576
+
1577
+ ```python
1578
+ Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
1579
+ emphasis=None, highlight=0)
1580
+ ```
1581
+
1582
+ ```python
1583
+
1584
+ Yes: if (width == 0 and height == 0 and
1585
+ color == 'red' and emphasis == 'strong'):
1586
+
1587
+ (bridge_questions.clarification_on
1588
+ .average_airspeed_of.unladen_swallow) = 'African or European?'
1589
+
1590
+ with (
1591
+ very_long_first_expression_function() as spam,
1592
+ very_long_second_expression_function() as beans,
1593
+ third_thing() as eggs,
1594
+ ):
1595
+ place_order(eggs, beans, spam, beans)
1596
+ ```
1597
+
1598
+ ```python
1599
+
1600
+ No: if width == 0 and height == 0 and \
1601
+ color == 'red' and emphasis == 'strong':
1602
+
1603
+ bridge_questions.clarification_on \
1604
+ .average_airspeed_of.unladen_swallow = 'African or European?'
1605
+
1606
+ with very_long_first_expression_function() as spam, \
1607
+ very_long_second_expression_function() as beans, \
1608
+ third_thing() as eggs:
1609
+ place_order(eggs, beans, spam, beans)
1610
+ ```
1611
+
1612
+ When a literal string won't fit on a single line, use parentheses for implicit
1613
+ line joining.
1614
+
1615
+ ```python
1616
+ x = ('This will build a very long long '
1617
+ 'long long long long long long string')
1618
+ ```
1619
+
1620
+ Prefer to break lines at the highest possible syntactic level. If you must break
1621
+ a line twice, break it at the same syntactic level both times.
1622
+
1623
+ ```python
1624
+ Yes: bridgekeeper.answer(
1625
+ name="Arthur", quest=questlib.find(owner="Arthur", perilous=True))
1626
+
1627
+ answer = (a_long_line().of_chained_methods()
1628
+ .that_eventually_provides().an_answer())
1629
+
1630
+ if (
1631
+ config is None
1632
+ or 'editor.language' not in config
1633
+ or config['editor.language'].use_spaces is False
1634
+ ):
1635
+ use_tabs()
1636
+ ```
1637
+
1638
+ ```python
1639
+ No: bridgekeeper.answer(name="Arthur", quest=questlib.find(
1640
+ owner="Arthur", perilous=True))
1641
+
1642
+ answer = a_long_line().of_chained_methods().that_eventually_provides(
1643
+ ).an_answer()
1644
+
1645
+ if (config is None or 'editor.language' not in config or config[
1646
+ 'editor.language'].use_spaces is False):
1647
+ use_tabs()
1648
+
1649
+ ```
1650
+
1651
+ Within comments, put long URLs on their own line if necessary.
1652
+
1653
+ ```python
1654
+ Yes: # See details at
1655
+ # http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
1656
+ ```
1657
+
1658
+ ```python
1659
+ No: # See details at
1660
+ # http://www.example.com/us/developer/documentation/api/content/\
1661
+ # v2.0/csv_file_name_extension_full_specification.html
1662
+ ```
1663
+
1664
+ Make note of the indentation of the elements in the line continuation examples
1665
+ above; see the [indentation](#s3.4-indentation) section for explanation.
1666
+
1667
+ [Docstring](#docstrings) summary lines must remain within the 80 character
1668
+ limit.
1669
+
1670
+ In all other cases where a line exceeds 80 characters, and the
1671
+ [Black](https://github.com/psf/black) or [Pyink](https://github.com/google/pyink)
1672
+ auto-formatter does not help bring the line below the limit, the line is allowed
1673
+ to exceed this maximum. Authors are encouraged to manually break the line up per
1674
+ the notes above when it is sensible.
1675
+
1676
+ <a id="s3.3-parentheses"></a>
1677
+ <a id="33-parentheses"></a>
1678
+
1679
+ <a id="parentheses"></a>
1680
+ ### 3.3 Parentheses
1681
+
1682
+ Use parentheses sparingly.
1683
+
1684
+ It is fine, though not required, to use parentheses around tuples. Do not use
1685
+ them in return statements or conditional statements unless using parentheses for
1686
+ implied line continuation or to indicate a tuple.
1687
+
1688
+ ```python
1689
+ Yes: if foo:
1690
+ bar()
1691
+ while x:
1692
+ x = bar()
1693
+ if x and y:
1694
+ bar()
1695
+ if not x:
1696
+ bar()
1697
+ # For a 1 item tuple the ()s are more visually obvious than the comma.
1698
+ onesie = (foo,)
1699
+ return foo
1700
+ return spam, beans
1701
+ return (spam, beans)
1702
+ for (x, y) in dict.items(): ...
1703
+ ```
1704
+
1705
+ ```python
1706
+ No: if (x):
1707
+ bar()
1708
+ if not(x):
1709
+ bar()
1710
+ return (foo)
1711
+ ```
1712
+
1713
+ <a id="s3.4-indentation"></a>
1714
+ <a id="34-indentation"></a>
1715
+
1716
+ <a id="indentation"></a>
1717
+ ### 3.4 Indentation
1718
+
1719
+ Indent your code blocks with *4 spaces*.
1720
+
1721
+ Never use tabs. Implied line continuation should align wrapped elements
1722
+ vertically (see [line length examples](#s3.2-line-length)), or use a hanging
1723
+ 4-space indent. Closing (round, square or curly) brackets can be placed at the
1724
+ end of the expression, or on separate lines, but then should be indented the
1725
+ same as the line with the corresponding opening bracket.
1726
+
1727
+ ```python
1728
+ Yes: # Aligned with opening delimiter.
1729
+ foo = long_function_name(var_one, var_two,
1730
+ var_three, var_four)
1731
+ meal = (spam,
1732
+ beans)
1733
+
1734
+ # Aligned with opening delimiter in a dictionary.
1735
+ foo = {
1736
+ 'long_dictionary_key': value1 +
1737
+ value2,
1738
+ ...
1739
+ }
1740
+
1741
+ # 4-space hanging indent; nothing on first line.
1742
+ foo = long_function_name(
1743
+ var_one, var_two, var_three,
1744
+ var_four)
1745
+ meal = (
1746
+ spam,
1747
+ beans)
1748
+
1749
+ # 4-space hanging indent; nothing on first line,
1750
+ # closing parenthesis on a new line.
1751
+ foo = long_function_name(
1752
+ var_one, var_two, var_three,
1753
+ var_four
1754
+ )
1755
+ meal = (
1756
+ spam,
1757
+ beans,
1758
+ )
1759
+
1760
+ # 4-space hanging indent in a dictionary.
1761
+ foo = {
1762
+ 'long_dictionary_key':
1763
+ long_dictionary_value,
1764
+ ...
1765
+ }
1766
+ ```
1767
+
1768
+ ```python
1769
+ No: # Stuff on first line forbidden.
1770
+ foo = long_function_name(var_one, var_two,
1771
+ var_three, var_four)
1772
+ meal = (spam,
1773
+ beans)
1774
+
1775
+ # 2-space hanging indent forbidden.
1776
+ foo = long_function_name(
1777
+ var_one, var_two, var_three,
1778
+ var_four)
1779
+
1780
+ # No hanging indent in a dictionary.
1781
+ foo = {
1782
+ 'long_dictionary_key':
1783
+ long_dictionary_value,
1784
+ ...
1785
+ }
1786
+ ```
1787
+
1788
+ <a id="s3.4.1-trailing-comma"></a>
1789
+ <a id="s3.4.1-trailing-commas"></a>
1790
+ <a id="s3.4.1-trailing_comma"></a>
1791
+ <a id="s3.4.1-trailing_commas"></a>
1792
+ <a id="341-trailing_comma"></a>
1793
+ <a id="341-trailing_commas"></a>
1794
+ <a id="trailing_comma"></a>
1795
+ <a id="trailing_commas"></a>
1796
+
1797
+ <a id="trailing-comma"></a>
1798
+ #### 3.4.1 Trailing commas in sequences of items?
1799
+
1800
+ Trailing commas in sequences of items are recommended only when the closing
1801
+ container token `]`, `)`, or `}` does not appear on the same line as the final
1802
+ element, as well as for tuples with a single element. The presence of a trailing
1803
+ comma is also used as a hint to our Python code auto-formatter
1804
+ [Black](https://github.com/psf/black) or [Pyink](https://github.com/google/pyink)
1805
+ to direct it to auto-format the container of items to one item per line when the
1806
+ `,` after the final element is present.
1807
+
1808
+ ```python
1809
+ Yes: golomb3 = [0, 1, 3]
1810
+ golomb4 = [
1811
+ 0,
1812
+ 1,
1813
+ 4,
1814
+ 6,
1815
+ ]
1816
+ ```
1817
+
1818
+ ```python
1819
+ No: golomb4 = [
1820
+ 0,
1821
+ 1,
1822
+ 4,
1823
+ 6,]
1824
+ ```
1825
+
1826
+ <a id="s3.5-blank-lines"></a>
1827
+ <a id="35-blank-lines"></a>
1828
+
1829
+ <a id="blank-lines"></a>
1830
+ ### 3.5 Blank Lines
1831
+
1832
+ Two blank lines between top-level definitions, be they function or class
1833
+ definitions. One blank line between method definitions and between the docstring
1834
+ of a `class` and the first method. No blank line following a `def` line. Use
1835
+ single blank lines as you judge appropriate within functions or methods.
1836
+
1837
+ Blank lines need not be anchored to the definition. For example, related
1838
+ comments immediately preceding function, class, and method definitions can make
1839
+ sense. Consider if your comment might be more useful as part of the docstring.
1840
+
1841
+ <a id="s3.6-whitespace"></a>
1842
+ <a id="36-whitespace"></a>
1843
+
1844
+ <a id="whitespace"></a>
1845
+ ### 3.6 Whitespace
1846
+
1847
+ Follow standard typographic rules for the use of spaces around punctuation.
1848
+
1849
+ No whitespace inside parentheses, brackets or braces.
1850
+
1851
+ ```python
1852
+ Yes: spam(ham[1], {'eggs': 2}, [])
1853
+ ```
1854
+
1855
+ ```python
1856
+ No: spam( ham[ 1 ], { 'eggs': 2 }, [ ] )
1857
+ ```
1858
+
1859
+ No whitespace before a comma, semicolon, or colon. Do use whitespace after a
1860
+ comma, semicolon, or colon, except at the end of the line.
1861
+
1862
+ ```python
1863
+ Yes: if x == 4:
1864
+ print(x, y)
1865
+ x, y = y, x
1866
+ ```
1867
+
1868
+ ```python
1869
+ No: if x == 4 :
1870
+ print(x , y)
1871
+ x , y = y , x
1872
+ ```
1873
+
1874
+ No whitespace before the open paren/bracket that starts an argument list,
1875
+ indexing or slicing.
1876
+
1877
+ ```python
1878
+ Yes: spam(1)
1879
+ ```
1880
+
1881
+ ```python
1882
+ No: spam (1)
1883
+ ```
1884
+
1885
+ ```python
1886
+ Yes: dict['key'] = list[index]
1887
+ ```
1888
+
1889
+ ```python
1890
+ No: dict ['key'] = list [index]
1891
+ ```
1892
+
1893
+ No trailing whitespace.
1894
+
1895
+ Surround binary operators with a single space on either side for assignment
1896
+ (`=`), comparisons (`==, <, >, !=, <>, <=, >=, in, not in, is, is not`), and
1897
+ Booleans (`and, or, not`). Use your better judgment for the insertion of spaces
1898
+ around arithmetic operators (`+`, `-`, `*`, `/`, `//`, `%`, `**`, `@`).
1899
+
1900
+ ```python
1901
+ Yes: x == 1
1902
+ ```
1903
+
1904
+ ```python
1905
+ No: x<1
1906
+ ```
1907
+
1908
+ Never use spaces around `=` when passing keyword arguments or defining a default
1909
+ parameter value, with one exception:
1910
+ [when a type annotation is present](#typing-default-values), *do* use spaces
1911
+ around the `=` for the default parameter value.
1912
+
1913
+ ```python
1914
+ Yes: def complex(real, imag=0.0): return Magic(r=real, i=imag)
1915
+ Yes: def complex(real, imag: float = 0.0): return Magic(r=real, i=imag)
1916
+ ```
1917
+
1918
+ ```python
1919
+ No: def complex(real, imag = 0.0): return Magic(r = real, i = imag)
1920
+ No: def complex(real, imag: float=0.0): return Magic(r = real, i = imag)
1921
+ ```
1922
+
1923
+ Don't use spaces to vertically align tokens on consecutive lines, since it
1924
+ becomes a maintenance burden (applies to `:`, `#`, `=`, etc.):
1925
+
1926
+ ```python
1927
+ Yes:
1928
+ foo = 1000 # comment
1929
+ long_name = 2 # comment that should not be aligned
1930
+
1931
+ dictionary = {
1932
+ 'foo': 1,
1933
+ 'long_name': 2,
1934
+ }
1935
+ ```
1936
+
1937
+ ```python
1938
+ No:
1939
+ foo = 1000 # comment
1940
+ long_name = 2 # comment that should not be aligned
1941
+
1942
+ dictionary = {
1943
+ 'foo' : 1,
1944
+ 'long_name': 2,
1945
+ }
1946
+ ```
1947
+
1948
+
1949
+ <a id="Python_Interpreter"></a>
1950
+ <a id="s3.7-shebang-line"></a>
1951
+ <a id="37-shebang-line"></a>
1952
+
1953
+ <a id="shebang-line"></a>
1954
+ ### 3.7 Shebang Line
1955
+
1956
+ Most `.py` files do not need to start with a `#!` line. Start the main file of a
1957
+ program with
1958
+ `#!/usr/bin/env python3` (to support virtualenvs) or `#!/usr/bin/python3` per
1959
+ [PEP-394](https://peps.python.org/pep-0394/).
1960
+
1961
+ This line is used by the kernel to find the Python interpreter, but is ignored by Python when importing modules. It is only necessary on a file intended to be executed directly.
1962
+
1963
+ <a id="s3.8-comments-and-docstrings"></a>
1964
+ <a id="s3.8-comments"></a>
1965
+ <a id="38-comments-and-docstrings"></a>
1966
+
1967
+ <a id="documentation"></a>
1968
+ ### 3.8 Comments and Docstrings
1969
+
1970
+ Be sure to use the right style for module, function, method docstrings and
1971
+ inline comments.
1972
+
1973
+ <a id="s3.8.1-comments-in-doc-strings"></a>
1974
+ <a id="381-docstrings"></a>
1975
+ <a id="comments-in-doc-strings"></a>
1976
+
1977
+ <a id="docstrings"></a>
1978
+ #### 3.8.1 Docstrings
1979
+
1980
+ Python uses *docstrings* to document code. A docstring is a string that is the
1981
+ first statement in a package, module, class or function. These strings can be
1982
+ extracted automatically through the `__doc__` member of the object and are used
1983
+ by `pydoc`.
1984
+ (Try running `pydoc` on your module to see how it looks.) Always use the
1985
+ three-double-quote `"""` format for docstrings (per
1986
+ [PEP 257](https://peps.python.org/pep-0257/)). A docstring should be organized
1987
+ as a summary line (one physical line not exceeding 80 characters) terminated by
1988
+ a period, question mark, or exclamation point. When writing more (encouraged),
1989
+ this must be followed by a blank line, followed by the rest of the docstring
1990
+ starting at the same cursor position as the first quote of the first line. There
1991
+ are more formatting guidelines for docstrings below.
1992
+
1993
+ <a id="s3.8.2-comments-in-modules"></a>
1994
+ <a id="382-modules"></a>
1995
+ <a id="comments-in-modules"></a>
1996
+
1997
+ <a id="module-docs"></a>
1998
+ #### 3.8.2 Modules
1999
+
2000
+ Every file should contain license boilerplate. Choose the appropriate boilerplate for the license used by the project (for example, Apache 2.0, BSD, LGPL, GPL).
2001
+
2002
+ Files should start with a docstring describing the contents and usage of the
2003
+ module.
2004
+ ```python
2005
+ """A one-line summary of the module or program, terminated by a period.
2006
+
2007
+ Leave one blank line. The rest of this docstring should contain an
2008
+ overall description of the module or program. Optionally, it may also
2009
+ contain a brief description of exported classes and functions and/or usage
2010
+ examples.
2011
+
2012
+ Typical usage example:
2013
+
2014
+ foo = ClassFoo()
2015
+ bar = foo.function_bar()
2016
+ """
2017
+ ```
2018
+
2019
+
2020
+ <a id="s3.8.2.1-test-modules"></a>
2021
+
2022
+ <a id="test-docs"></a>
2023
+ ##### 3.8.2.1 Test modules
2024
+
2025
+ Module-level docstrings for test files are not required. They should be included
2026
+ only when there is additional information that can be provided.
2027
+
2028
+ Examples include some specifics on how the test should be run, an explanation of
2029
+ an unusual setup pattern, dependency on the external environment, and so on.
2030
+
2031
+ ```python
2032
+ """This blaze test uses golden files.
2033
+
2034
+ You can update those files by running
2035
+ `blaze run //foo/bar:foo_test -- --update_golden_files` from the `google3`
2036
+ directory.
2037
+ """
2038
+ ```
2039
+
2040
+ Docstrings that do not provide any new information should not be used.
2041
+
2042
+ ```python
2043
+ """Tests for foo.bar."""
2044
+ ```
2045
+
2046
+ <a id="s3.8.3-functions-and-methods"></a>
2047
+ <a id="383-functions-and-methods"></a>
2048
+ <a id="functions-and-methods"></a>
2049
+
2050
+ <a id="function-docs"></a>
2051
+ #### 3.8.3 Functions and Methods
2052
+
2053
+ In this section, "function" means a method, function, generator, or property.
2054
+
2055
+ A docstring is mandatory for every function that has one or more of the
2056
+ following properties:
2057
+
2058
+ - being part of the public API
2059
+ - nontrivial size
2060
+ - non-obvious logic
2061
+
2062
+ A docstring should give enough information to write a call to the function
2063
+ without reading the function's code. The docstring should describe the
2064
+ function's calling syntax and its semantics, but generally not its
2065
+ implementation details, unless those details are relevant to how the function is
2066
+ to be used. For example, a function that mutates one of its arguments as a side
2067
+ effect should note that in its docstring. Otherwise, subtle but important
2068
+ details of a function's implementation that are not relevant to the caller are
2069
+ better expressed as comments alongside the code than within the function's
2070
+ docstring.
2071
+
2072
+ The docstring may be descriptive-style (`"""Fetches rows from a Bigtable."""`)
2073
+ or imperative-style (`"""Fetch rows from a Bigtable."""`), but the style should
2074
+ be consistent within a file. The docstring for a `@property` data descriptor
2075
+ should use the same style as the docstring for an attribute or a
2076
+ <a href="#doc-function-args">function argument</a> (`"""The Bigtable path."""`,
2077
+ rather than `"""Returns the Bigtable path."""`).
2078
+
2079
+ Certain aspects of a function should be documented in special sections, listed
2080
+ below. Each section begins with a heading line, which ends with a colon. All
2081
+ sections other than the heading should maintain a hanging indent of two or four
2082
+ spaces (be consistent within a file). These sections can be omitted in cases
2083
+ where the function's name and signature are informative enough that it can be
2084
+ aptly described using a one-line docstring.
2085
+
2086
+ <a id="doc-function-args"></a>
2087
+ [*Args:*](#doc-function-args)
2088
+ : List each parameter by name. A description should follow the name, and be
2089
+ separated by a colon followed by either a space or newline. If the
2090
+ description is too long to fit on a single 80-character line, use a hanging
2091
+ indent of 2 or 4 spaces more than the parameter name (be consistent with the
2092
+ rest of the docstrings in the file). The description should include required
2093
+ type(s) if the code does not contain a corresponding type annotation. If a
2094
+ function accepts `*foo` (variable length argument lists) and/or `**bar`
2095
+ (arbitrary keyword arguments), they should be listed as `*foo` and `**bar`.
2096
+
2097
+ <a id="doc-function-returns"></a>
2098
+ [*Returns:* (or *Yields:* for generators)](#doc-function-returns)
2099
+ : Describe the semantics of the return value, including any type information
2100
+ that the type annotation does not provide. If the function only returns
2101
+ None, this section is not required. It may also be omitted if the docstring
2102
+ starts with "Return", "Returns", "Yield", or "Yields" (e.g. `"""Returns row
2103
+ from Bigtable as a tuple of strings."""`) *and* the opening sentence is
2104
+ sufficient to describe the return value. Do not imitate older 'NumPy style'
2105
+ ([example](https://numpy.org/doc/1.24/reference/generated/numpy.linalg.qr.html)),
2106
+ which frequently documented a tuple return value as if it were multiple
2107
+ return values with individual names (never mentioning the tuple). Instead,
2108
+ describe such a return value as: "Returns: A tuple (mat_a, mat_b), where
2109
+ mat_a is ..., and ...". The auxiliary names in the docstring need not
2110
+ necessarily correspond to any internal names used in the function body (as
2111
+ those are not part of the API). If the function uses `yield` (is a
2112
+ generator), the `Yields:` section should document the object returned by
2113
+ `next()`, instead of the generator object itself that the call evaluates to.
2114
+
2115
+ <a id="doc-function-raises"></a>
2116
+ [*Raises:*](#doc-function-raises)
2117
+ : List all exceptions that are relevant to the interface followed by a
2118
+ description. Use a similar exception name + colon + space or newline and
2119
+ hanging indent style as described in *Args:*. You should not document
2120
+ exceptions that get raised if the API specified in the docstring is violated
2121
+ (because this would paradoxically make behavior under violation of the API
2122
+ part of the API).
2123
+
2124
+ ```python
2125
+ def fetch_smalltable_rows(
2126
+ table_handle: smalltable.Table,
2127
+ keys: Sequence[bytes | str],
2128
+ require_all_keys: bool = False,
2129
+ ) -> Mapping[bytes, tuple[str, ...]]:
2130
+ """Fetches rows from a Smalltable.
2131
+
2132
+ Retrieves rows pertaining to the given keys from the Table instance
2133
+ represented by table_handle. String keys will be UTF-8 encoded.
2134
+
2135
+ Args:
2136
+ table_handle: An open smalltable.Table instance.
2137
+ keys: A sequence of strings representing the key of each table
2138
+ row to fetch. String keys will be UTF-8 encoded.
2139
+ require_all_keys: If True only rows with values set for all keys will be
2140
+ returned.
2141
+
2142
+ Returns:
2143
+ A dict mapping keys to the corresponding table row data
2144
+ fetched. Each row is represented as a tuple of strings. For
2145
+ example:
2146
+
2147
+ {b'Serak': ('Rigel VII', 'Preparer'),
2148
+ b'Zim': ('Irk', 'Invader'),
2149
+ b'Lrrr': ('Omicron Persei 8', 'Emperor')}
2150
+
2151
+ Returned keys are always bytes. If a key from the keys argument is
2152
+ missing from the dictionary, then that row was not found in the
2153
+ table (and require_all_keys must have been False).
2154
+
2155
+ Raises:
2156
+ IOError: An error occurred accessing the smalltable.
2157
+ """
2158
+ ```
2159
+
2160
+ Similarly, this variation on `Args:` with a line break is also allowed:
2161
+
2162
+ ```python
2163
+ def fetch_smalltable_rows(
2164
+ table_handle: smalltable.Table,
2165
+ keys: Sequence[bytes | str],
2166
+ require_all_keys: bool = False,
2167
+ ) -> Mapping[bytes, tuple[str, ...]]:
2168
+ """Fetches rows from a Smalltable.
2169
+
2170
+ Retrieves rows pertaining to the given keys from the Table instance
2171
+ represented by table_handle. String keys will be UTF-8 encoded.
2172
+
2173
+ Args:
2174
+ table_handle:
2175
+ An open smalltable.Table instance.
2176
+ keys:
2177
+ A sequence of strings representing the key of each table row to
2178
+ fetch. String keys will be UTF-8 encoded.
2179
+ require_all_keys:
2180
+ If True only rows with values set for all keys will be returned.
2181
+
2182
+ Returns:
2183
+ A dict mapping keys to the corresponding table row data
2184
+ fetched. Each row is represented as a tuple of strings. For
2185
+ example:
2186
+
2187
+ {b'Serak': ('Rigel VII', 'Preparer'),
2188
+ b'Zim': ('Irk', 'Invader'),
2189
+ b'Lrrr': ('Omicron Persei 8', 'Emperor')}
2190
+
2191
+ Returned keys are always bytes. If a key from the keys argument is
2192
+ missing from the dictionary, then that row was not found in the
2193
+ table (and require_all_keys must have been False).
2194
+
2195
+ Raises:
2196
+ IOError: An error occurred accessing the smalltable.
2197
+ """
2198
+ ```
2199
+
2200
+ <a id="s3.8.3.1-overridden-methods"></a>
2201
+
2202
+ <a id="overridden-method-docs"></a>
2203
+ ##### 3.8.3.1 Overridden Methods
2204
+
2205
+ A method that overrides a method from a base class does not need a docstring if
2206
+ it is explicitly decorated with
2207
+ [`@override`](https://typing-extensions.readthedocs.io/en/latest/#override)
2208
+ (from `typing_extensions` or `typing` modules), unless the overriding method's
2209
+ behavior materially refines the base method's contract, or details need to be
2210
+ provided (e.g., documenting additional side effects), in which case a docstring
2211
+ with at least those differences is required on the overriding method.
2212
+
2213
+ ```python
2214
+ from typing_extensions import override
2215
+
2216
+ class Parent:
2217
+ def do_something(self):
2218
+ """Parent method, includes docstring."""
2219
+
2220
+ # Child class, method annotated with override.
2221
+ class Child(Parent):
2222
+ @override
2223
+ def do_something(self):
2224
+ pass
2225
+ ```
2226
+
2227
+ ```python
2228
+ # Child class, but without @override decorator, a docstring is required.
2229
+ class Child(Parent):
2230
+ def do_something(self):
2231
+ pass
2232
+
2233
+ # Docstring is trivial, @override is sufficient to indicate that docs can be
2234
+ # found in the base class.
2235
+ class Child(Parent):
2236
+ @override
2237
+ def do_something(self):
2238
+ """See base class."""
2239
+ ```
2240
+
2241
+ <a id="s3.8.4-comments-in-classes"></a>
2242
+ <a id="384-classes"></a>
2243
+ <a id="comments-in-classes"></a>
2244
+
2245
+ <a id="class-docs"></a>
2246
+ #### 3.8.4 Classes
2247
+
2248
+ Classes should have a docstring below the class definition describing the class.
2249
+ Public attributes, excluding [properties](#properties), should be documented
2250
+ here in an `Attributes` section and follow the same formatting as a
2251
+ [function's `Args`](#doc-function-args) section.
2252
+
2253
+ ```python
2254
+ class SampleClass:
2255
+ """Summary of class here.
2256
+
2257
+ Longer class information...
2258
+ Longer class information...
2259
+
2260
+ Attributes:
2261
+ likes_spam: A boolean indicating if we like SPAM or not.
2262
+ eggs: An integer count of the eggs we have laid.
2263
+ """
2264
+
2265
+ def __init__(self, likes_spam: bool = False):
2266
+ """Initializes the instance based on spam preference.
2267
+
2268
+ Args:
2269
+ likes_spam: Defines if instance exhibits this preference.
2270
+ """
2271
+ self.likes_spam = likes_spam
2272
+ self.eggs = 0
2273
+
2274
+ @property
2275
+ def butter_sticks(self) -> int:
2276
+ """The number of butter sticks we have."""
2277
+ ```
2278
+
2279
+ All class docstrings should start with a one-line summary that describes what
2280
+ the class instance represents. This implies that subclasses of `Exception`
2281
+ should also describe what the exception represents, and not the context in which
2282
+ it might occur. The class docstring should not repeat unnecessary information,
2283
+ such as that the class is a class.
2284
+
2285
+ ```python
2286
+ # Yes:
2287
+ class CheeseShopAddress:
2288
+ """The address of a cheese shop.
2289
+
2290
+ ...
2291
+ """
2292
+
2293
+ class OutOfCheeseError(Exception):
2294
+ """No more cheese is available."""
2295
+ ```
2296
+
2297
+ ```python
2298
+ # No:
2299
+ class CheeseShopAddress:
2300
+ """Class that describes the address of a cheese shop.
2301
+
2302
+ ...
2303
+ """
2304
+
2305
+ class OutOfCheeseError(Exception):
2306
+ """Raised when no more cheese is available."""
2307
+ ```
2308
+
2309
+ <a id="s3.8.5-block-and-inline-comments"></a>
2310
+ <a id="comments-in-block-and-inline"></a>
2311
+ <a id="s3.8.5-comments-in-block-and-inline"></a>
2312
+ <a id="385-block-and-inline-comments"></a>
2313
+
2314
+ <a id="comments"></a>
2315
+ #### 3.8.5 Block and Inline Comments
2316
+
2317
+ The final place to have comments is in tricky parts of the code. If you're going
2318
+ to have to explain it at the next [code review](http://en.wikipedia.org/wiki/Code_review),
2319
+ you should comment it now. Complicated operations get a few lines of comments
2320
+ before the operations commence. Non-obvious ones get comments at the end of the
2321
+ line.
2322
+
2323
+ ```python
2324
+ # We use a weighted dictionary search to find out where i is in
2325
+ # the array. We extrapolate position based on the largest num
2326
+ # in the array and the array size and then do binary search to
2327
+ # get the exact number.
2328
+
2329
+ if i & (i-1) == 0: # True if i is 0 or a power of 2.
2330
+ ```
2331
+
2332
+ To improve legibility, these comments should start at least 2 spaces away from
2333
+ the code with the comment character `#`, followed by at least one space before
2334
+ the text of the comment itself.
2335
+
2336
+ On the other hand, never describe the code. Assume the person reading the code
2337
+ knows Python (though not what you're trying to do) better than you do.
2338
+
2339
+ ```python
2340
+ # BAD COMMENT: Now go through the b array and make sure whenever i occurs
2341
+ # the next element is i+1
2342
+ ```
2343
+
2344
+ <!-- The next section is copied from the C++ style guide. -->
2345
+
2346
+ <a id="s3.8.6-punctuation-spelling-and-grammar"></a>
2347
+ <a id="386-punctuation-spelling-and-grammar"></a>
2348
+ <a id="spelling"></a>
2349
+ <a id="punctuation"></a>
2350
+ <a id="grammar"></a>
2351
+
2352
+ <a id="punctuation-spelling-grammar"></a>
2353
+ #### 3.8.6 Punctuation, Spelling, and Grammar
2354
+
2355
+ Pay attention to punctuation, spelling, and grammar; it is easier to read
2356
+ well-written comments than badly written ones.
2357
+
2358
+ Comments should be as readable as narrative text, with proper capitalization and
2359
+ punctuation. In many cases, complete sentences are more readable than sentence
2360
+ fragments. Shorter comments, such as comments at the end of a line of code, can
2361
+ sometimes be less formal, but you should be consistent with your style.
2362
+
2363
+ Although it can be frustrating to have a code reviewer point out that you are
2364
+ using a comma when you should be using a semicolon, it is very important that
2365
+ source code maintain a high level of clarity and readability. Proper
2366
+ punctuation, spelling, and grammar help with that goal.
2367
+
2368
+ <a id="s3.10-strings"></a>
2369
+ <a id="310-strings"></a>
2370
+
2371
+ <a id="strings"></a>
2372
+ ### 3.10 Strings
2373
+
2374
+ Use an
2375
+ [f-string](https://docs.python.org/3/reference/lexical_analysis.html#f-strings),
2376
+ the `%` operator, or the `format` method for formatting strings, even when the
2377
+ parameters are all strings. Use your best judgment to decide between string
2378
+ formatting options. A single join with `+` is okay but do not format with `+`.
2379
+
2380
+ ```python
2381
+ Yes: x = f'name: {name}; score: {n}'
2382
+ x = '%s, %s!' % (imperative, expletive)
2383
+ x = '{}, {}'.format(first, second)
2384
+ x = 'name: %s; score: %d' % (name, n)
2385
+ x = 'name: %(name)s; score: %(score)d' % {'name':name, 'score':n}
2386
+ x = 'name: {}; score: {}'.format(name, n)
2387
+ x = a + b
2388
+ ```
2389
+
2390
+ ```python
2391
+ No: x = first + ', ' + second
2392
+ x = 'name: ' + name + '; score: ' + str(n)
2393
+ ```
2394
+
2395
+ Avoid using the `+` and `+=` operators to accumulate a string within a loop. In
2396
+ some conditions, accumulating a string with addition can lead to quadratic
2397
+ rather than linear running time. Although common accumulations of this sort may
2398
+ be optimized on CPython, that is an implementation detail. The conditions under
2399
+ which an optimization applies are not easy to predict and may change. Instead,
2400
+ add each substring to a list and `''.join` the list after the loop terminates,
2401
+ or write each substring to an `io.StringIO` buffer. These techniques
2402
+ consistently have amortized-linear run-time complexity.
2403
+
2404
+ ```python
2405
+ Yes: items = ['<table>']
2406
+ for last_name, first_name in employee_list:
2407
+ items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
2408
+ items.append('</table>')
2409
+ employee_table = ''.join(items)
2410
+ ```
2411
+
2412
+ ```python
2413
+ No: employee_table = '<table>'
2414
+ for last_name, first_name in employee_list:
2415
+ employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
2416
+ employee_table += '</table>'
2417
+ ```
2418
+
2419
+ Be consistent with your choice of string quote character within a file. Pick `'`
2420
+ or `"` and stick with it. It is okay to use the other quote character on a
2421
+ string to avoid the need to backslash-escape quote characters within the string.
2422
+
2423
+ ```python
2424
+ Yes:
2425
+ Python('Why are you hiding your eyes?')
2426
+ Gollum("I'm scared of lint errors.")
2427
+ Narrator('"Good!" thought a happy Python reviewer.')
2428
+ ```
2429
+
2430
+ ```python
2431
+ No:
2432
+ Python("Why are you hiding your eyes?")
2433
+ Gollum('The lint. It burns. It burns us.')
2434
+ Gollum("Always the great lint. Watching. Watching.")
2435
+ ```
2436
+
2437
+ Prefer `"""` for multi-line strings rather than `'''`. Projects may choose to
2438
+ use `'''` for all non-docstring multi-line strings if and only if they also use
2439
+ `'` for regular strings. Docstrings must use `"""` regardless.
2440
+
2441
+ Multi-line strings do not flow with the indentation of the rest of the program.
2442
+ If you need to avoid embedding extra space in the string, use either
2443
+ concatenated single-line strings or a multi-line string with
2444
+ [`textwrap.dedent()`](https://docs.python.org/3/library/textwrap.html#textwrap.dedent)
2445
+ to remove the initial space on each line:
2446
+
2447
+ ```python
2448
+ No:
2449
+ long_string = """This is pretty ugly.
2450
+ Don't do this.
2451
+ """
2452
+ ```
2453
+
2454
+ ```python
2455
+ Yes:
2456
+ long_string = """This is fine if your use case can accept
2457
+ extraneous leading spaces."""
2458
+ ```
2459
+
2460
+ ```python
2461
+ Yes:
2462
+ long_string = ("And this is fine if you cannot accept\n" +
2463
+ "extraneous leading spaces.")
2464
+ ```
2465
+
2466
+ ```python
2467
+ Yes:
2468
+ long_string = ("And this too is fine if you cannot accept\n"
2469
+ "extraneous leading spaces.")
2470
+ ```
2471
+
2472
+ ```python
2473
+ Yes:
2474
+ import textwrap
2475
+
2476
+ long_string = textwrap.dedent("""\
2477
+ This is also fine, because textwrap.dedent()
2478
+ will collapse common leading spaces in each line.""")
2479
+ ```
2480
+
2481
+ Note that using a backslash here does not violate the prohibition against
2482
+ [explicit line continuation](#line-length); in this case, the backslash is
2483
+ [escaping a newline](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals)
2484
+ in a string literal.
2485
+
2486
+ <a id="s3.10.1-logging"></a>
2487
+ <a id="3101-logging"></a>
2488
+ <a id="logging"></a>
2489
+
2490
+ <a id="logging"></a>
2491
+ #### 3.10.1 Logging
2492
+
2493
+ For logging functions that expect a pattern-string (with %-placeholders) as
2494
+ their first argument: Always call them with a string literal (not an f-string!)
2495
+ as their first argument with pattern-parameters as subsequent arguments. Some
2496
+ logging implementations collect the unexpanded pattern-string as a queryable
2497
+ field. It also prevents spending time rendering a message that no logger is
2498
+ configured to output.
2499
+
2500
+ ```python
2501
+ Yes:
2502
+ import tensorflow as tf
2503
+ logger = tf.get_logger()
2504
+ logger.info('TensorFlow Version is: %s', tf.__version__)
2505
+ ```
2506
+
2507
+ ```python
2508
+ Yes:
2509
+ import os
2510
+ from absl import logging
2511
+
2512
+ logging.info('Current $PAGER is: %s', os.getenv('PAGER', default=''))
2513
+
2514
+ homedir = os.getenv('HOME')
2515
+ if homedir is None or not os.access(homedir, os.W_OK):
2516
+ logging.error('Cannot write to home directory, $HOME=%r', homedir)
2517
+ ```
2518
+
2519
+ ```python
2520
+ No:
2521
+ import os
2522
+ from absl import logging
2523
+
2524
+ logging.info('Current $PAGER is:')
2525
+ logging.info(os.getenv('PAGER', default=''))
2526
+
2527
+ homedir = os.getenv('HOME')
2528
+ if homedir is None or not os.access(homedir, os.W_OK):
2529
+ logging.error(f'Cannot write to home directory, $HOME={homedir!r}')
2530
+ ```
2531
+
2532
+ <a id="s3.10.2-error-messages"></a>
2533
+ <a id="3102-error-messages"></a>
2534
+ <a id="error-messages"></a>
2535
+
2536
+ <a id="error-messages"></a>
2537
+ #### 3.10.2 Error Messages
2538
+
2539
+ Error messages (such as: message strings on exceptions like `ValueError`, or
2540
+ messages shown to the user) should follow three guidelines:
2541
+
2542
+ 1. The message needs to precisely match the actual error condition.
2543
+
2544
+ 2. Interpolated pieces need to always be clearly identifiable as such.
2545
+
2546
+ 3. They should allow simple automated processing (e.g. grepping).
2547
+
2548
+ ```python
2549
+ Yes:
2550
+ if not 0 <= p <= 1:
2551
+ raise ValueError(f'Not a probability: {p=}')
2552
+
2553
+ try:
2554
+ os.rmdir(workdir)
2555
+ except OSError as error:
2556
+ logging.warning('Could not remove directory (reason: %r): %r',
2557
+ error, workdir)
2558
+ ```
2559
+
2560
+ ```python
2561
+ No:
2562
+ if p < 0 or p > 1: # PROBLEM: also false for float('nan')!
2563
+ raise ValueError(f'Not a probability: {p=}')
2564
+
2565
+ try:
2566
+ os.rmdir(workdir)
2567
+ except OSError:
2568
+ # PROBLEM: Message makes an assumption that might not be true:
2569
+ # Deletion might have failed for some other reason, misleading
2570
+ # whoever has to debug this.
2571
+ logging.warning('Directory already was deleted: %s', workdir)
2572
+
2573
+ try:
2574
+ os.rmdir(workdir)
2575
+ except OSError:
2576
+ # PROBLEM: The message is harder to grep for than necessary, and
2577
+ # not universally non-confusing for all possible values of `workdir`.
2578
+ # Imagine someone calling a library function with such code
2579
+ # using a name such as workdir = 'deleted'. The warning would read:
2580
+ # "The deleted directory could not be deleted."
2581
+ logging.warning('The %s directory could not be deleted.', workdir)
2582
+ ```
2583
+
2584
+ <a id="s3.11-files-sockets-closeables"></a>
2585
+ <a id="s3.11-files-and-sockets"></a>
2586
+ <a id="311-files-and-sockets"></a>
2587
+ <a id="files-and-sockets"></a>
2588
+
2589
+ <a id="files"></a>
2590
+ ### 3.11 Files, Sockets, and similar Stateful Resources
2591
+
2592
+ Explicitly close files and sockets when done with them. This rule naturally
2593
+ extends to closeable resources that internally use sockets, such as database
2594
+ connections, and also other resources that need to be closed down in a similar
2595
+ fashion. To name only a few examples, this also includes
2596
+ [mmap](https://docs.python.org/3/library/mmap.html) mappings,
2597
+ [h5py File objects](https://docs.h5py.org/en/stable/high/file.html), and
2598
+ [matplotlib.pyplot figure windows](https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html).
2599
+
2600
+ Leaving files, sockets or other such stateful objects open unnecessarily has
2601
+ many downsides:
2602
+
2603
+ - They may consume limited system resources, such as file descriptors. Code
2604
+ that deals with many such objects may exhaust those resources unnecessarily
2605
+ if they're not returned to the system promptly after use.
2606
+ - Holding files open may prevent other actions such as moving or deleting
2607
+ them, or unmounting a filesystem.
2608
+ - Files and sockets that are shared throughout a program may inadvertently be
2609
+ read from or written to after logically being closed. If they are actually
2610
+ closed, attempts to read or write from them will raise exceptions, making
2611
+ the problem known sooner.
2612
+
2613
+ Furthermore, while files and sockets (and some similarly behaving resources) are
2614
+ automatically closed when the object is destructed, coupling the lifetime of the
2615
+ object to the state of the resource is poor practice:
2616
+
2617
+ - There are no guarantees as to when the runtime will actually invoke the
2618
+ `__del__` method. Different Python implementations use different memory
2619
+ management techniques, such as delayed garbage collection, which may
2620
+ increase the object's lifetime arbitrarily and indefinitely.
2621
+ - Unexpected references to the file, e.g. in globals or exception tracebacks,
2622
+ may keep it around longer than intended.
2623
+
2624
+ Relying on finalizers to do automatic cleanup that has observable side effects
2625
+ has been rediscovered over and over again to lead to major problems, across many
2626
+ decades and multiple languages (see e.g.
2627
+ [this article](https://wiki.sei.cmu.edu/confluence/display/java/MET12-J.+Do+not+use+finalizers)
2628
+ for Java).
2629
+
2630
+ The preferred way to manage files and similar resources is using the
2631
+ [`with` statement](http://docs.python.org/reference/compound_stmts.html#the-with-statement):
2632
+
2633
+ ```python
2634
+ with open("hello.txt") as hello_file:
2635
+ for line in hello_file:
2636
+ print(line)
2637
+ ```
2638
+
2639
+ For file-like objects that do not support the `with` statement, use
2640
+ `contextlib.closing()`:
2641
+
2642
+ ```python
2643
+ import contextlib
2644
+
2645
+ with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
2646
+ for line in front_page:
2647
+ print(line)
2648
+ ```
2649
+
2650
+ In rare cases where context-based resource management is infeasible, code
2651
+ documentation must explain clearly how resource lifetime is managed.
2652
+
2653
+ <a id="s3.12-todo-comments"></a>
2654
+ <a id="312-todo-comments"></a>
2655
+
2656
+ <a id="todo"></a>
2657
+ ### 3.12 TODO Comments
2658
+
2659
+ Use `TODO` comments for code that is temporary, a short-term solution, or
2660
+ good-enough but not perfect.
2661
+
2662
+ A `TODO` comment begins with the word `TODO` in all caps, a following colon, and
2663
+ a link to a resource that contains the context, ideally a bug reference. A bug
2664
+ reference is preferable because bugs are tracked and have follow-up comments.
2665
+ Follow this piece of context with an explanatory string introduced with a hyphen
2666
+ `-`.
2667
+ The purpose is to have a consistent `TODO` format that can be searched to find
2668
+ out how to get more details.
2669
+
2670
+ ```python
2671
+ # TODO: crbug.com/192795 - Investigate cpufreq optimizations.
2672
+ ```
2673
+
2674
+ Old style, formerly recommended, but discouraged for use in new code:
2675
+
2676
+
2677
+ ```python
2678
+ # TODO(crbug.com/192795): Investigate cpufreq optimizations.
2679
+ # TODO(yourusername): Use a "\*" here for concatenation operator.
2680
+ ```
2681
+
2682
+ Avoid adding TODOs that refer to an individual or team as the context:
2683
+
2684
+ ```python
2685
+ # TODO: @yourusername - File an issue and use a '*' for repetition.
2686
+ ```
2687
+
2688
+ If your `TODO` is of the form "At a future date do something" make sure that you
2689
+ either include a very specific date ("Fix by November 2009") or a very specific
2690
+ event ("Remove this code when all clients can handle XML responses.") that
2691
+ future code maintainers will comprehend. Issues are ideal for tracking this.
2692
+
2693
+ <a id="s3.13-imports-formatting"></a>
2694
+ <a id="313-imports-formatting"></a>
2695
+
2696
+ <a id="imports-formatting"></a>
2697
+ ### 3.13 Imports formatting
2698
+
2699
+ Imports should be on separate lines; there are
2700
+ [exceptions for `typing` and `collections.abc` imports](#typing-imports).
2701
+
2702
+ E.g.:
2703
+
2704
+ ```python
2705
+ Yes: from collections.abc import Mapping, Sequence
2706
+ import os
2707
+ import sys
2708
+ from typing import Any, NewType
2709
+ ```
2710
+
2711
+ ```python
2712
+ No: import os, sys
2713
+ ```
2714
+
2715
+
2716
+ Imports are always put at the top of the file, just after any module comments
2717
+ and docstrings and before module globals and constants. Imports should be
2718
+ grouped from most generic to least generic:
2719
+
2720
+ 1. Python future import statements. For example:
2721
+
2722
+ ```python
2723
+ from __future__ import annotations
2724
+ ```
2725
+
2726
+ See [above](#from-future-imports) for more information about those.
2727
+
2728
+ 2. Python standard library imports. For example:
2729
+
2730
+ ```python
2731
+ import sys
2732
+ ```
2733
+
2734
+ 3. [third-party](https://pypi.org/) module
2735
+ or package imports. For example:
2736
+
2737
+
2738
+ ```python
2739
+ import tensorflow as tf
2740
+ ```
2741
+
2742
+ 4. Code repository
2743
+ sub-package imports. For example:
2744
+
2745
+
2746
+ ```python
2747
+ from otherproject.ai import mind
2748
+ ```
2749
+
2750
+ 5. **Deprecated:** application-specific imports that are part of the same
2751
+ top-level
2752
+ sub-package as this file. For example:
2753
+
2754
+
2755
+ ```python
2756
+ from myproject.backend.hgwells import time_machine
2757
+ ```
2758
+
2759
+ You may find older Google Python Style code doing this, but it is no longer
2760
+ required. **New code is encouraged not to bother with this.** Simply treat
2761
+ application-specific sub-package imports the same as other sub-package
2762
+ imports.
2763
+
2764
+
2765
+ Within each grouping, imports should be sorted lexicographically, ignoring case,
2766
+ according to each module's full package path (the `path` in `from path import
2767
+ ...`). Code may optionally place a blank line between import sections.
2768
+
2769
+ ```python
2770
+ import collections
2771
+ import queue
2772
+ import sys
2773
+
2774
+ from absl import app
2775
+ from absl import flags
2776
+ import bs4
2777
+ import cryptography
2778
+ import tensorflow as tf
2779
+
2780
+ from book.genres import scifi
2781
+ from myproject.backend import huxley
2782
+ from myproject.backend.hgwells import time_machine
2783
+ from myproject.backend.state_machine import main_loop
2784
+ from otherproject.ai import body
2785
+ from otherproject.ai import mind
2786
+ from otherproject.ai import soul
2787
+
2788
+ # Older style code may have these imports down here instead:
2789
+ #from myproject.backend.hgwells import time_machine
2790
+ #from myproject.backend.state_machine import main_loop
2791
+ ```
2792
+
2793
+
2794
+ <a id="s3.14-statements"></a>
2795
+ <a id="314-statements"></a>
2796
+
2797
+ <a id="statements"></a>
2798
+ ### 3.14 Statements
2799
+
2800
+ Generally only one statement per line.
2801
+
2802
+ However, you may put the result of a test on the same line as the test only if
2803
+ the entire statement fits on one line. In particular, you can never do so with
2804
+ `try`/`except` since the `try` and `except` can't both fit on the same line, and
2805
+ you can only do so with an `if` if there is no `else`.
2806
+
2807
+ ```python
2808
+ Yes:
2809
+
2810
+ if foo: bar(foo)
2811
+ ```
2812
+
2813
+ ```python
2814
+ No:
2815
+
2816
+ if foo: bar(foo)
2817
+ else: baz(foo)
2818
+
2819
+ try: bar(foo)
2820
+ except ValueError: baz(foo)
2821
+
2822
+ try:
2823
+ bar(foo)
2824
+ except ValueError: baz(foo)
2825
+ ```
2826
+
2827
+ <a id="s3.15-accessors"></a>
2828
+ <a id="s3.15-access-control"></a>
2829
+ <a id="315-access-control"></a>
2830
+ <a id="access-control"></a>
2831
+ <a id="accessors"></a>
2832
+
2833
+ <a id="getters-and-setters"></a>
2834
+ ### 3.15 Getters and Setters
2835
+
2836
+ Getter and setter functions (also called accessors and mutators) should be used
2837
+ when they provide a meaningful role or behavior for getting or setting a
2838
+ variable's value.
2839
+
2840
+ In particular, they should be used when getting or setting the variable is
2841
+ complex or the cost is significant, either currently or in a reasonable future.
2842
+
2843
+ If, for example, a pair of getters/setters simply read and write an internal
2844
+ attribute, the internal attribute should be made public instead. By comparison,
2845
+ if setting a variable means some state is invalidated or rebuilt, it should be a
2846
+ setter function. The function invocation hints that a potentially non-trivial
2847
+ operation is occurring. Alternatively, [properties](#properties) may be an
2848
+ option when simple logic is needed, or refactoring to no longer need getters and
2849
+ setters.
2850
+
2851
+ Getters and setters should follow the [Naming](#s3.16-naming) guidelines, such
2852
+ as `get_foo()` and `set_foo()`.
2853
+
2854
+ If the past behavior allowed access through a property, do not bind the new
2855
+ getter/setter functions to the property. Any code still attempting to access the
2856
+ variable by the old method should break visibly so they are made aware of the
2857
+ change in complexity.
2858
+
2859
+ <a id="s3.16-naming"></a>
2860
+ <a id="316-naming"></a>
2861
+
2862
+ <a id="naming"></a>
2863
+ ### 3.16 Naming
2864
+
2865
+ `module_name`, `package_name`, `ClassName`, `method_name`, `ExceptionName`,
2866
+ `function_name`, `GLOBAL_CONSTANT_NAME`, `global_var_name`, `instance_var_name`,
2867
+ `function_parameter_name`, `local_var_name`, `query_proper_noun_for_thing`,
2868
+ `send_acronym_via_https`.
2869
+
2870
+
2871
+ Names should be descriptive. This includes functions, classes, variables,
2872
+ attributes, files and any other type of named entities.
2873
+
2874
+ Avoid abbreviation. In particular, do not use abbreviations that are ambiguous
2875
+ or unfamiliar to readers outside your project, and do not abbreviate by deleting
2876
+ letters within a word.
2877
+
2878
+ Always use a `.py` filename extension. Never use dashes.
2879
+
2880
+ <a id="s3.16.1-names-to-avoid"></a>
2881
+ <a id="3161-names-to-avoid"></a>
2882
+
2883
+ <a id="names-to-avoid"></a>
2884
+ #### 3.16.1 Names to Avoid
2885
+
2886
+ - single character names, except for specifically allowed cases:
2887
+
2888
+ - counters or iterators (e.g. `i`, `j`, `k`, `v`, et al.)
2889
+ - `e` as an exception identifier in `try/except` statements.
2890
+ - `f` as a file handle in `with` statements
2891
+ - private [type variables](#typing-type-var) with no constraints (e.g.
2892
+ `_T = TypeVar("_T")`, `_P = ParamSpec("_P")`)
2893
+ - names that match established notation in a reference paper or algorithm
2894
+ (see [Mathematical Notation](#math-notation))
2895
+
2896
+ Please be mindful not to abuse single-character naming. Generally speaking,
2897
+ descriptiveness should be proportional to the name's scope of visibility.
2898
+ For example, `i` might be a fine name for 5-line code block but within
2899
+ multiple nested scopes, it is likely too vague.
2900
+
2901
+ - dashes (`-`) in any package/module name
2902
+
2903
+ - `__double_leading_and_trailing_underscore__` names (reserved by Python)
2904
+
2905
+ - offensive terms
2906
+
2907
+ - names that needlessly include the type of the variable (for example:
2908
+ `id_to_name_dict`)
2909
+
2910
+ <a id="s3.16.2-naming-conventions"></a>
2911
+ <a id="3162-naming-convention"></a>
2912
+
2913
+ <a id="naming-conventions"></a>
2914
+ #### 3.16.2 Naming Conventions
2915
+
2916
+ - "Internal" means internal to a module, or protected or private within a
2917
+ class.
2918
+
2919
+ - Prepending a single underscore (`_`) has some support for protecting module
2920
+ variables and functions (linters will flag protected member access). Note
2921
+ that it is okay for unit tests to access protected constants from the
2922
+ modules under test.
2923
+
2924
+ - Prepending a double underscore (`__` aka "dunder") to an instance variable
2925
+ or method effectively makes the variable or method private to its class
2926
+ (using name mangling); we discourage its use as it impacts readability and
2927
+ testability, and isn't *really* private. Prefer a single underscore.
2928
+
2929
+ - Place related classes and top-level functions together in a
2930
+ module.
2931
+ Unlike Java, there is no need to limit yourself to one class per module.
2932
+
2933
+ - Use CapWords for class names, but lower\_with\_under.py for module names.
2934
+ Although there are some old modules named CapWords.py, this is now
2935
+ discouraged because it's confusing when the module happens to be named after
2936
+ a class. ("wait -- did I write `import StringIO` or `from StringIO import
2937
+ StringIO`?")
2938
+
2939
+ - New *unit test* files follow PEP 8 compliant lower\_with\_under method
2940
+ names, for example, `test_<method_under_test>_<state>`. For consistency(\*)
2941
+ with legacy modules that follow CapWords function names, underscores may
2942
+ appear in method names starting with `test` to separate logical components
2943
+ of the name. One possible pattern is `test<MethodUnderTest>_<state>`.
2944
+
2945
+ <a id="s3.16.3-file-naming"></a>
2946
+ <a id="3163-file-naming"></a>
2947
+
2948
+ <a id="file-naming"></a>
2949
+ #### 3.16.3 File Naming
2950
+
2951
+ Python filenames must have a `.py` extension and must not contain dashes (`-`).
2952
+ This allows them to be imported and unittested. If you want an executable to be
2953
+ accessible without the extension, use a symbolic link or a simple bash wrapper
2954
+ containing `exec "$0.py" "$@"`.
2955
+
2956
+ <a id="s3.16.4-guidelines-derived-from-guidos-recommendations"></a>
2957
+ <a id="3164-guidelines-derived-from-guidos-recommendations"></a>
2958
+
2959
+ <a id="guidelines-derived-from-guidos-recommendations"></a>
2960
+ #### 3.16.4 Guidelines derived from [Guido](https://en.wikipedia.org/wiki/Guido_van_Rossum)'s Recommendations
2961
+
2962
+ <table rules="all" border="1" summary="Guidelines from Guido's Recommendations"
2963
+ cellspacing="2" cellpadding="2">
2964
+
2965
+ <tr>
2966
+ <th>Type</th>
2967
+ <th>Public</th>
2968
+ <th>Internal</th>
2969
+ </tr>
2970
+
2971
+ <tr>
2972
+ <td>Packages</td>
2973
+ <td><code>lower_with_under</code></td>
2974
+ <td></td>
2975
+ </tr>
2976
+
2977
+ <tr>
2978
+ <td>Modules</td>
2979
+ <td><code>lower_with_under</code></td>
2980
+ <td><code>_lower_with_under</code></td>
2981
+ </tr>
2982
+
2983
+ <tr>
2984
+ <td>Classes</td>
2985
+ <td><code>CapWords</code></td>
2986
+ <td><code>_CapWords</code></td>
2987
+ </tr>
2988
+
2989
+ <tr>
2990
+ <td>Exceptions</td>
2991
+ <td><code>CapWords</code></td>
2992
+ <td></td>
2993
+ </tr>
2994
+
2995
+ <tr>
2996
+ <td>Functions</td>
2997
+ <td><code>lower_with_under()</code></td>
2998
+ <td><code>_lower_with_under()</code></td>
2999
+ </tr>
3000
+
3001
+ <tr>
3002
+ <td>Global/Class Constants</td>
3003
+ <td><code>CAPS_WITH_UNDER</code></td>
3004
+ <td><code>_CAPS_WITH_UNDER</code></td>
3005
+ </tr>
3006
+
3007
+ <tr>
3008
+ <td>Global/Class Variables</td>
3009
+ <td><code>lower_with_under</code></td>
3010
+ <td><code>_lower_with_under</code></td>
3011
+ </tr>
3012
+
3013
+ <tr>
3014
+ <td>Instance Variables</td>
3015
+ <td><code>lower_with_under</code></td>
3016
+ <td><code>_lower_with_under</code> (protected)</td>
3017
+ </tr>
3018
+
3019
+ <tr>
3020
+ <td>Method Names</td>
3021
+ <td><code>lower_with_under()</code></td>
3022
+ <td><code>_lower_with_under()</code> (protected)</td>
3023
+ </tr>
3024
+
3025
+ <tr>
3026
+ <td>Function/Method Parameters</td>
3027
+ <td><code>lower_with_under</code></td>
3028
+ <td></td>
3029
+ </tr>
3030
+
3031
+ <tr>
3032
+ <td>Local Variables</td>
3033
+ <td><code>lower_with_under</code></td>
3034
+ <td></td>
3035
+ </tr>
3036
+
3037
+ </table>
3038
+
3039
+
3040
+ <a id="s3.17-main"></a>
3041
+ <a id="317-main"></a>
3042
+
3043
+ <a id="math-notation"></a>
3044
+ #### 3.16.5 Mathematical Notation
3045
+
3046
+ For mathematically-heavy code, short variable names that would otherwise violate
3047
+ the style guide are preferred when they match established notation in a
3048
+ reference paper or algorithm.
3049
+
3050
+ When using names based on established notation:
3051
+
3052
+ 1. Cite the source of all naming conventions, preferably with a hyperlink to
3053
+ academic resource itself, in a comment or docstring. If the source is not
3054
+ accessible, clearly document the naming conventions.
3055
+ 2. Prefer PEP8-compliant `descriptive_names` for public APIs, which are much
3056
+ more likely to be encountered out of context.
3057
+ 3. Use a narrowly-scoped `pylint: disable=invalid-name` directive to silence
3058
+ warnings. For just a few variables, use the directive as an endline comment
3059
+ for each one; for more, apply the directive at the beginning of a block.
3060
+
3061
+ <a id="main"></a>
3062
+ ### 3.17 Main
3063
+
3064
+ In Python, `pydoc` as well as unit tests require modules to be importable. If a
3065
+ file is meant to be used as an executable, its main functionality should be in a
3066
+ `main()` function, and your code should always check `if __name__ == '__main__'`
3067
+ before executing your main program, so that it is not executed when the module
3068
+ is imported.
3069
+
3070
+ When using [absl](https://github.com/abseil/abseil-py), use `app.run`:
3071
+
3072
+ ```python
3073
+ from absl import app
3074
+ ...
3075
+
3076
+ def main(argv: Sequence[str]):
3077
+ # process non-flag arguments
3078
+ ...
3079
+
3080
+ if __name__ == '__main__':
3081
+ app.run(main)
3082
+ ```
3083
+
3084
+ Otherwise, use:
3085
+
3086
+ ```python
3087
+ def main():
3088
+ ...
3089
+
3090
+ if __name__ == '__main__':
3091
+ main()
3092
+ ```
3093
+
3094
+ All code at the top level will be executed when the module is imported. Be
3095
+ careful not to call functions, create objects, or perform other operations that
3096
+ should not be executed when the file is being `pydoc`ed.
3097
+
3098
+ <a id="s3.18-function-length"></a>
3099
+ <a id="318-function-length"></a>
3100
+
3101
+ <a id="function-length"></a>
3102
+ ### 3.18 Function length
3103
+
3104
+ Prefer small and focused functions.
3105
+
3106
+ We recognize that long functions are sometimes appropriate, so no hard limit is
3107
+ placed on function length. If a function exceeds about 40 lines, think about
3108
+ whether it can be broken up without harming the structure of the program.
3109
+
3110
+ Even if your long function works perfectly now, someone modifying it in a few
3111
+ months may add new behavior. This could result in bugs that are hard to find.
3112
+ Keeping your functions short and simple makes it easier for other people to read
3113
+ and modify your code.
3114
+
3115
+ You could find long and complicated functions when working with
3116
+ some
3117
+ code. Do not be intimidated by modifying existing code: if working with such a
3118
+ function proves to be difficult, you find that errors are hard to debug, or you
3119
+ want to use a piece of it in several different contexts, consider breaking up
3120
+ the function into smaller and more manageable pieces.
3121
+
3122
+ <a id="s3.19-type-annotations"></a>
3123
+ <a id="319-type-annotations"></a>
3124
+
3125
+ <a id="type-annotations"></a>
3126
+ ### 3.19 Type Annotations
3127
+
3128
+ <a id="s3.19.1-general-rules"></a>
3129
+ <a id="s3.19.1-general"></a>
3130
+ <a id="3191-general-rules"></a>
3131
+
3132
+ <a id="typing-general"></a>
3133
+ #### 3.19.1 General Rules
3134
+
3135
+ * Familiarize yourself with
3136
+ [type hints](https://docs.python.org/3/library/typing.html).
3137
+
3138
+ * Annotating `self` or `cls` is generally not necessary.
3139
+ [`Self`](https://docs.python.org/3/library/typing.html#typing.Self) can be
3140
+ used if it is necessary for proper type information, e.g.
3141
+
3142
+ ```python
3143
+ from typing import Self
3144
+
3145
+ class BaseClass:
3146
+ @classmethod
3147
+ def create(cls) -> Self:
3148
+ ...
3149
+
3150
+ def difference(self, other: Self) -> float:
3151
+ ...
3152
+ ```
3153
+
3154
+ * Similarly, don't feel compelled to annotate the return value of `__init__`
3155
+ (where `None` is the only valid option).
3156
+
3157
+ * If any other variable or a returned type should not be expressed, use `Any`.
3158
+
3159
+ * You are not required to annotate all the functions in a module.
3160
+
3161
+ - At least annotate your public APIs.
3162
+ - Use judgment to get to a good balance between safety and clarity on the
3163
+ one hand, and flexibility on the other.
3164
+ - Annotate code that is prone to type-related errors (previous bugs or
3165
+ complexity).
3166
+ - Annotate code that is hard to understand.
3167
+ - Annotate code as it becomes stable from a types perspective. In many
3168
+ cases, you can annotate all the functions in mature code without losing
3169
+ too much flexibility.
3170
+
3171
+ <a id="s3.19.2-line-breaking"></a>
3172
+ <a id="3192-line-breaking"></a>
3173
+
3174
+ <a id="typing-line-breaking"></a>
3175
+ #### 3.19.2 Line Breaking
3176
+
3177
+ Try to follow the existing [indentation](#indentation) rules.
3178
+
3179
+ After annotating, many function signatures will become "one parameter per line".
3180
+ To ensure the return type is also given its own line, a comma can be placed
3181
+ after the last parameter.
3182
+
3183
+ ```python
3184
+ def my_method(
3185
+ self,
3186
+ first_var: int,
3187
+ second_var: Foo,
3188
+ third_var: Bar | None,
3189
+ ) -> int:
3190
+ ...
3191
+ ```
3192
+
3193
+ Always prefer breaking between variables, and not, for example, between variable
3194
+ names and type annotations. However, if everything fits on the same line, go for
3195
+ it.
3196
+
3197
+ ```python
3198
+ def my_method(self, first_var: int) -> int:
3199
+ ...
3200
+ ```
3201
+
3202
+ If the combination of the function name, the last parameter, and the return type
3203
+ is too long, indent by 4 in a new line. When using line breaks, prefer putting
3204
+ each parameter and the return type on their own lines and aligning the closing
3205
+ parenthesis with the `def`:
3206
+
3207
+ ```python
3208
+ Yes:
3209
+ def my_method(
3210
+ self,
3211
+ other_arg: MyLongType | None,
3212
+ ) -> tuple[MyLongType1, MyLongType1]:
3213
+ ...
3214
+ ```
3215
+
3216
+ Optionally, the return type may be put on the same line as the last parameter:
3217
+
3218
+ ```python
3219
+ Okay:
3220
+ def my_method(
3221
+ self,
3222
+ first_var: int,
3223
+ second_var: int) -> dict[OtherLongType, MyLongType]:
3224
+ ...
3225
+ ```
3226
+
3227
+ `pylint`
3228
+ allows you to move the closing parenthesis to a new line and align with the
3229
+ opening one, but this is less readable.
3230
+
3231
+ ```python
3232
+ No:
3233
+ def my_method(self,
3234
+ other_arg: MyLongType | None,
3235
+ ) -> dict[OtherLongType, MyLongType]:
3236
+ ...
3237
+ ```
3238
+
3239
+ As in the examples above, prefer not to break types. However, sometimes they are
3240
+ too long to be on a single line (try to keep sub-types unbroken).
3241
+
3242
+ ```python
3243
+ def my_method(
3244
+ self,
3245
+ first_var: tuple[list[MyLongType1],
3246
+ list[MyLongType2]],
3247
+ second_var: list[dict[
3248
+ MyLongType3, MyLongType4]],
3249
+ ) -> None:
3250
+ ...
3251
+ ```
3252
+
3253
+ If a single name and type is too long, consider using an
3254
+ [alias](#typing-aliases) for the type. The last resort is to break after the
3255
+ colon and indent by 4.
3256
+
3257
+ ```python
3258
+ Yes:
3259
+ def my_function(
3260
+ long_variable_name:
3261
+ long_module_name.LongTypeName,
3262
+ ) -> None:
3263
+ ...
3264
+ ```
3265
+
3266
+ ```python
3267
+ No:
3268
+ def my_function(
3269
+ long_variable_name: long_module_name.
3270
+ LongTypeName,
3271
+ ) -> None:
3272
+ ...
3273
+ ```
3274
+
3275
+ <a id="s3.19.3-forward-declarations"></a>
3276
+ <a id="3193-forward-declarations"></a>
3277
+
3278
+ <a id="forward-declarations"></a>
3279
+ #### 3.19.3 Forward Declarations
3280
+
3281
+ If you need to use a class name (from the same module) that is not yet
3282
+ defined -- for example, if you need the class name inside the declaration of
3283
+ that class, or if you use a class that is defined later in the code -- either
3284
+ use `from __future__ import annotations` or use a string for the class name.
3285
+
3286
+ ```python
3287
+ Yes:
3288
+ from __future__ import annotations
3289
+
3290
+ class MyClass:
3291
+ def __init__(self, stack: Sequence[MyClass], item: OtherClass) -> None:
3292
+
3293
+ class OtherClass:
3294
+ ...
3295
+ ```
3296
+
3297
+ ```python
3298
+ Yes:
3299
+ class MyClass:
3300
+ def __init__(self, stack: Sequence['MyClass'], item: 'OtherClass') -> None:
3301
+
3302
+ class OtherClass:
3303
+ ...
3304
+ ```
3305
+
3306
+ <a id="s3.19.4-default-values"></a>
3307
+ <a id="3194-default-values"></a>
3308
+
3309
+ <a id="typing-default-values"></a>
3310
+ #### 3.19.4 Default Values
3311
+
3312
+ As per [PEP-008](https://peps.python.org/pep-0008/#other-recommendations), use
3313
+ spaces around the `=` *only* for arguments that have both a type annotation and
3314
+ a default value.
3315
+
3316
+ ```python
3317
+ Yes:
3318
+ def func(a: int = 0) -> int:
3319
+ ...
3320
+ ```
3321
+
3322
+ ```python
3323
+ No:
3324
+ def func(a:int=0) -> int:
3325
+ ...
3326
+ ```
3327
+
3328
+ <a id="s3.19.5-nonetype"></a>
3329
+ <a id="s3.19.5-none-type"></a>
3330
+ <a id="3195-nonetype"></a>
3331
+
3332
+ <a id="none-type"></a>
3333
+ #### 3.19.5 NoneType
3334
+
3335
+ In the Python type system, `NoneType` is a "first class" type, and for typing
3336
+ purposes, `None` is an alias for `NoneType`. If an argument can be `None`, it
3337
+ has to be declared! You can use `|` union type expressions (recommended in new
3338
+ Python 3.10+ code), or the older `Optional` and `Union` syntaxes.
3339
+
3340
+ Use explicit `X | None` instead of implicit. Earlier versions of type checkers
3341
+ allowed `a: str = None` to be interpreted as `a: str | None = None`, but that is
3342
+ no longer the preferred behavior.
3343
+
3344
+ ```python
3345
+ Yes:
3346
+ def modern_or_union(a: str | int | None, b: str | None = None) -> str:
3347
+ ...
3348
+ def union_optional(a: Union[str, int, None], b: Optional[str] = None) -> str:
3349
+ ...
3350
+ ```
3351
+
3352
+ ```python
3353
+ No:
3354
+ def nullable_union(a: Union[None, str]) -> str:
3355
+ ...
3356
+ def implicit_optional(a: str = None) -> str:
3357
+ ...
3358
+ ```
3359
+
3360
+ <a id="s3.19.6-type-aliases"></a>
3361
+ <a id="s3.19.6-aliases"></a>
3362
+ <a id="3196-type-aliases"></a>
3363
+ <a id="typing-aliases"></a>
3364
+
3365
+ <a id="type-aliases"></a>
3366
+ #### 3.19.6 Type Aliases
3367
+
3368
+ You can declare aliases of complex types. The name of an alias should be
3369
+ CapWorded. If the alias is used only in this module, it should be \_Private.
3370
+
3371
+ Note that the `: TypeAlias` annotation is only supported in versions 3.10+.
3372
+
3373
+ ```python
3374
+ from typing import TypeAlias
3375
+
3376
+ _LossAndGradient: TypeAlias = tuple[tf.Tensor, tf.Tensor]
3377
+ ComplexTFMap: TypeAlias = Mapping[str, _LossAndGradient]
3378
+ ```
3379
+
3380
+ <a id="s3.19.7-ignoring-types"></a>
3381
+ <a id="s3.19.7-ignore"></a>
3382
+ <a id="3197-ignoring-types"></a>
3383
+
3384
+ <a id="typing-ignore"></a>
3385
+ #### 3.19.7 Ignoring Types
3386
+
3387
+ You can disable type checking on a line with the special comment `# type:
3388
+ ignore`.
3389
+
3390
+ `pytype` has a disable option for specific errors (similar to lint):
3391
+
3392
+ ```python
3393
+ # pytype: disable=attribute-error
3394
+ ```
3395
+
3396
+ <a id="s3.19.8-typing-variables"></a>
3397
+ <a id="s3.19.8-comments"></a>
3398
+ <a id="3198-typing-internal-variables"></a>
3399
+
3400
+ <a id="typing-variables"></a>
3401
+ #### 3.19.8 Typing Variables
3402
+
3403
+ <a id="annotated-assignments"></a>
3404
+ [*Annotated Assignments*](#annotated-assignments)
3405
+ : If an internal variable has a type that is hard or impossible to infer,
3406
+ specify its type with an annotated assignment - use a colon and type between
3407
+ the variable name and value (the same as is done with function arguments
3408
+ that have a default value):
3409
+
3410
+ ```python
3411
+ a: Foo = SomeUndecoratedFunction()
3412
+ ```
3413
+
3414
+ <a id="type-comments"></a>
3415
+ [*Type Comments*](#type-comments)
3416
+ : Though you may see them remaining in the codebase (they were necessary
3417
+ before Python 3.6), do not add any more uses of a `# type: <type name>`
3418
+ comment on the end of the line:
3419
+
3420
+ ```python
3421
+ a = SomeUndecoratedFunction() # type: Foo
3422
+ ```
3423
+
3424
+ <a id="s3.19.9-tuples-vs-lists"></a>
3425
+ <a id="s3.19.9-tuples"></a>
3426
+ <a id="3199-tuples-vs-lists"></a>
3427
+
3428
+ <a id="typing-tuples"></a>
3429
+ #### 3.19.9 Tuples vs Lists
3430
+
3431
+ Typed lists can only contain objects of a single type. Typed tuples can either
3432
+ have a single repeated type or a set number of elements with different types.
3433
+ The latter is commonly used as the return type from a function.
3434
+
3435
+ ```python
3436
+ a: list[int] = [1, 2, 3]
3437
+ b: tuple[int, ...] = (1, 2, 3)
3438
+ c: tuple[int, str, float] = (1, "2", 3.5)
3439
+ ```
3440
+
3441
+ <a id="s3.19.10-typevars"></a>
3442
+ <a id="s3.19.10-type-var"></a>
3443
+ <a id="31910-typevar"></a>
3444
+ <a id="typing-type-var"></a>
3445
+
3446
+ <a id="typevars"></a>
3447
+ #### 3.19.10 Type variables
3448
+
3449
+ The Python type system has
3450
+ [generics](https://docs.python.org/3/library/typing.html#generics). A type
3451
+ variable, such as `TypeVar` and `ParamSpec`, is a common way to use them.
3452
+
3453
+ Example:
3454
+
3455
+ ```python
3456
+ from collections.abc import Callable
3457
+ from typing import ParamSpec, TypeVar
3458
+ _P = ParamSpec("_P")
3459
+ _T = TypeVar("_T")
3460
+ ...
3461
+ def next(l: list[_T]) -> _T:
3462
+ return l.pop()
3463
+
3464
+ def print_when_called(f: Callable[_P, _T]) -> Callable[_P, _T]:
3465
+ def inner(*args: _P.args, **kwargs: _P.kwargs) -> _T:
3466
+ print("Function was called")
3467
+ return f(*args, **kwargs)
3468
+ return inner
3469
+ ```
3470
+
3471
+ A `TypeVar` can be constrained:
3472
+
3473
+ ```python
3474
+ AddableType = TypeVar("AddableType", int, float, str)
3475
+ def add(a: AddableType, b: AddableType) -> AddableType:
3476
+ return a + b
3477
+ ```
3478
+
3479
+ A common predefined type variable in the `typing` module is `AnyStr`. Use it for
3480
+ multiple annotations that can be `bytes` or `str` and must all be the same type.
3481
+
3482
+ ```python
3483
+ from typing import AnyStr
3484
+ def check_length(x: AnyStr) -> AnyStr:
3485
+ if len(x) <= 42:
3486
+ return x
3487
+ raise ValueError()
3488
+ ```
3489
+
3490
+ A type variable must have a descriptive name, unless it meets all of the
3491
+ following criteria:
3492
+
3493
+ * not externally visible
3494
+ * not constrained
3495
+
3496
+ ```python
3497
+ Yes:
3498
+ _T = TypeVar("_T")
3499
+ _P = ParamSpec("_P")
3500
+ AddableType = TypeVar("AddableType", int, float, str)
3501
+ AnyFunction = TypeVar("AnyFunction", bound=Callable)
3502
+ ```
3503
+
3504
+ ```python
3505
+ No:
3506
+ T = TypeVar("T")
3507
+ P = ParamSpec("P")
3508
+ _T = TypeVar("_T", int, float, str)
3509
+ _F = TypeVar("_F", bound=Callable)
3510
+ ```
3511
+
3512
+ <a id="s3.19.11-string-types"></a>
3513
+ <a id="s3.19.11-strings"></a>
3514
+ <a id="31911-string-types"></a>
3515
+
3516
+ <a id="typing-strings"></a>
3517
+ #### 3.19.11 String types
3518
+
3519
+ > Do not use `typing.Text` in new code. It's only for Python 2/3 compatibility.
3520
+
3521
+ Use `str` for string/text data. For code that deals with binary data, use
3522
+ `bytes`.
3523
+
3524
+ ```python
3525
+ def deals_with_text_data(x: str) -> str:
3526
+ ...
3527
+ def deals_with_binary_data(x: bytes) -> bytes:
3528
+ ...
3529
+ ```
3530
+
3531
+ If all the string types of a function are always the same, for example if the
3532
+ return type is the same as the argument type in the code above, use
3533
+ [AnyStr](#typing-type-var).
3534
+
3535
+ <a id="s3.19.12-imports-for-typing"></a>
3536
+ <a id="s3.19.12-imports"></a>
3537
+ <a id="31912-imports-for-typing"></a>
3538
+
3539
+ <a id="typing-imports"></a>
3540
+ #### 3.19.12 Imports For Typing
3541
+
3542
+ For symbols (including types, functions, and constants) from the `typing` or
3543
+ `collections.abc` modules used to support static analysis and type checking,
3544
+ always import the symbol itself. This keeps common annotations more concise and
3545
+ matches typing practices used around the world. You are explicitly allowed to
3546
+ import multiple specific symbols on one line from the `typing` and
3547
+ `collections.abc` modules. For example:
3548
+
3549
+ ```python
3550
+ from collections.abc import Mapping, Sequence
3551
+ from typing import Any, Generic, cast, TYPE_CHECKING
3552
+ ```
3553
+
3554
+ Given that this way of importing adds items to the local namespace, names in
3555
+ `typing` or `collections.abc` should be treated similarly to keywords, and not
3556
+ be defined in your Python code, typed or not. If there is a collision between a
3557
+ type and an existing name in a module, import it using `import x as y`.
3558
+
3559
+ ```python
3560
+ from typing import Any as AnyType
3561
+ ```
3562
+
3563
+ When annotating function signatures, prefer abstract container types like
3564
+ `collections.abc.Sequence` over concrete types like `list`. If you need to use a
3565
+ concrete type (for example, a `tuple` of typed elements), prefer built-in types
3566
+ like `tuple` over the parametric type aliases from the `typing` module (e.g.,
3567
+ `typing.Tuple`).
3568
+
3569
+ ```python
3570
+ from typing import List, Tuple
3571
+
3572
+ def transform_coordinates(original: List[Tuple[float, float]]) ->
3573
+ List[Tuple[float, float]]:
3574
+ ...
3575
+ ```
3576
+
3577
+ ```python
3578
+ from collections.abc import Sequence
3579
+
3580
+ def transform_coordinates(original: Sequence[tuple[float, float]]) ->
3581
+ Sequence[tuple[float, float]]:
3582
+ ...
3583
+ ```
3584
+
3585
+ <a id="s3.19.13-conditional-imports"></a>
3586
+ <a id="31913-conditional-imports"></a>
3587
+
3588
+ <a id="typing-conditional-imports"></a>
3589
+ #### 3.19.13 Conditional Imports
3590
+
3591
+ Use conditional imports only in exceptional cases where the additional imports
3592
+ needed for type checking must be avoided at runtime. This pattern is
3593
+ discouraged; alternatives such as refactoring the code to allow top-level
3594
+ imports should be preferred.
3595
+
3596
+ Imports that are needed only for type annotations can be placed within an `if
3597
+ TYPE_CHECKING:` block.
3598
+
3599
+ - Conditionally imported types need to be referenced as strings, to be forward
3600
+ compatible with Python 3.6 where the annotation expressions are actually
3601
+ evaluated.
3602
+ - Only entities that are used solely for typing should be defined here; this
3603
+ includes aliases. Otherwise it will be a runtime error, as the module will
3604
+ not be imported at runtime.
3605
+ - The block should be right after all the normal imports.
3606
+ - There should be no empty lines in the typing imports list.
3607
+ - Sort this list as if it were a regular imports list.
3608
+ ```python
3609
+ import typing
3610
+ if typing.TYPE_CHECKING:
3611
+ import sketch
3612
+ def f(x: "sketch.Sketch"): ...
3613
+ ```
3614
+
3615
+ <a id="s3.19.14-circular-dependencies"></a>
3616
+ <a id="s3.19.14-circular-deps"></a>
3617
+ <a id="31914-circular-dependencies"></a>
3618
+
3619
+ <a id="typing-circular-deps"></a>
3620
+ #### 3.19.14 Circular Dependencies
3621
+
3622
+ Circular dependencies that are caused by typing are code smells. Such code is a
3623
+ good candidate for refactoring. Although technically it is possible to keep
3624
+ circular dependencies, various build systems will not let you do so
3625
+ because each module has to depend on the other.
3626
+
3627
+ Replace modules that create circular dependency imports with `Any`. Set an
3628
+ [alias](#typing-aliases) with a meaningful name, and use the real type name from
3629
+ this module (any attribute of `Any` is `Any`). Alias definitions should be
3630
+ separated from the last import by one line.
3631
+
3632
+ ```python
3633
+ from typing import Any
3634
+
3635
+ some_mod = Any # some_mod.py imports this module.
3636
+ ...
3637
+
3638
+ def my_method(self, var: "some_mod.SomeType") -> None:
3639
+ ...
3640
+ ```
3641
+
3642
+ <a id="typing-generics"></a>
3643
+ <a id="s3.19.15-generics"></a>
3644
+ <a id="31915-generics"></a>
3645
+
3646
+ <a id="generics"></a>
3647
+ #### 3.19.15 Generics
3648
+
3649
+ When annotating, prefer to specify type parameters for
3650
+ [generic](https://docs.python.org/3/library/typing.html#generics) types in a
3651
+ parameter list; otherwise, the generics' parameters will be assumed to be
3652
+ [`Any`](https://docs.python.org/3/library/typing.html#the-any-type).
3653
+
3654
+ ```python
3655
+ # Yes:
3656
+ def get_names(employee_ids: Sequence[int]) -> Mapping[int, str]:
3657
+ ...
3658
+ ```
3659
+
3660
+ ```python
3661
+ # No:
3662
+ # This is interpreted as get_names(employee_ids: Sequence[Any]) -> Mapping[Any, Any]
3663
+ def get_names(employee_ids: Sequence) -> Mapping:
3664
+ ...
3665
+ ```
3666
+
3667
+ If the best type parameter for a generic is `Any`, make it explicit, but
3668
+ remember that in many cases [`TypeVar`](#typing-type-var) might be more
3669
+ appropriate:
3670
+
3671
+ ```python
3672
+ # No:
3673
+ def get_names(employee_ids: Sequence[Any]) -> Mapping[Any, str]:
3674
+ """Returns a mapping from employee ID to employee name for given IDs."""
3675
+ ```
3676
+
3677
+ ```python
3678
+ # Yes:
3679
+ _T = TypeVar('_T')
3680
+ def get_names(employee_ids: Sequence[_T]) -> Mapping[_T, str]:
3681
+ """Returns a mapping from employee ID to employee name for given IDs."""
3682
+ ```
3683
+
3684
+
3685
+ <a id="4-parting-words"></a>
3686
+
3687
+ <a id="consistency"></a>
3688
+ ## 4 Parting Words
3689
+
3690
+ *BE CONSISTENT*.
3691
+
3692
+ If you're editing code, take a few minutes to look at the code around you and
3693
+ determine its style. If they use `_idx` suffixes in index variable names, you
3694
+ should too. If their comments have little boxes of hash marks around them, make
3695
+ your comments have little boxes of hash marks around them too.
3696
+
3697
+ The point of having style guidelines is to have a common vocabulary of coding so
3698
+ people can concentrate on what you're saying rather than on how you're saying
3699
+ it. We present global style rules here so people know the vocabulary, but local
3700
+ style is also important. If code you add to a file looks drastically different
3701
+ from the existing code around it, it throws readers out of their rhythm when
3702
+ they go to read it.
3703
+
3704
+ However, there are limits to consistency. It applies more heavily locally and on
3705
+ choices unspecified by the global style. Consistency should not generally be
3706
+ used as a justification to do things in an old style without considering the
3707
+ benefits of the new style, or the tendency of the codebase to converge on newer
3708
+ styles over time.
3709
+