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