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