@@ -212,12 +212,7 @@ that the arguments are actually unused.
212212### 2.2 Imports
213213
214214Use ` import ` statements for packages and modules only, not for individual
215- classes or functions. Classes imported from the
216- [ ` typing ` module] ( #typing-imports ) , [ ` collections.abc ` module] ( #typing-imports ) ,
217- [ ` typing_extensions ` module] ( https://github.com/python/typing/tree/master/typing_extensions ) ,
218- and redirects from the
219- [ six.moves module] ( https://six.readthedocs.io/#module-six.moves )
220- are exempt from this rule.
215+ classes or functions.
221216
222217<a id =" s2.2.1-definition " ></a >
223218<a id =" 221-definition " ></a >
@@ -272,6 +267,18 @@ Do not use relative names in imports. Even if the module is in the same package,
272267use the full package name. This helps prevent unintentionally importing a
273268package twice.
274269
270+ <a id =" imports-exemptions " ></a >
271+ ##### 2.2.4.1 Exemptions
272+
273+ Exemptions from this rule:
274+
275+ * Classes imported from the [ ` typing ` module] ( #typing-imports ) .
276+ * Classes imported from the [ ` collections.abc ` module] ( #typing-imports ) .
277+ * Classes imported from the
278+ [ ` typing_extensions ` module] ( https://github.com/python/typing/tree/HEAD/typing_extensions ) .
279+ * Redirects from the
280+ [ six.moves module] ( https://six.readthedocs.io/#module-six.moves ) .
281+
275282<a id =" s2.3-packages " ></a >
276283<a id =" 23-packages " ></a >
277284
@@ -722,14 +729,12 @@ Yes: for key in adict: ...
722729 if obj in alist: ...
723730 for line in afile: ...
724731 for k, v in adict.items(): ...
725- for k, v in six.iteritems(adict): ...
726732```
727733
728734```python
729735No: for key in adict.keys(): ...
730736 if not adict.has_key(key): ...
731737 for line in afile.readlines(): ...
732- for k, v in dict .iteritems(): ...
733738```
734739
735740< a id =" s2.9-generators" >< / a>
@@ -744,7 +749,7 @@ Use generators as needed.
744749< a id =" 291-definition" >< / a>
745750
746751< a id =" generators-definition" >< / a>
747- # ### 2.9 Definition
752+ # ### 2.9.1 Definition
748753
749754A generator function returns an iterator that yields a value each time it
750755executes a yield statement. After it yields a value, the runtime state of the
@@ -766,7 +771,8 @@ creates an entire list of values at once.
766771< a id =" generators-cons" >< / a>
767772# ### 2.9.3 Cons
768773
769- None .
774+ Local variables in the generator will not be garbage collected until the
775+ generator is either consumed to exhaustion or itself garbage collected.
770776
771777< a id =" s2.9.4-decision" >< / a>
772778< a id =" 294-decision" >< / a>
@@ -777,6 +783,11 @@ None.
777783Fine. Use " Yields:" rather than " Returns:" in the docstring for generator
778784functions.
779785
786+ If the generator manages an expensive resource, make sure to force the clean up.
787+
788+ A good way to do the clean up is by wrapping the generator with a context
789+ manager [PEP - 0533 ](https:// peps.python.org/ pep- 0533 / ).
790+
780791< a id =" s2.10-lambda-functions" >< / a>
781792< a id =" 210-lambda-functions" >< / a>
782793
@@ -1415,14 +1426,6 @@ In code that may execute on versions as old as 3.5 rather than >= 3.7, import:
14151426from __future__ import generator_stop
14161427```
14171428
1418- For legacy code with the burden of continuing to support 2.7 , import :
1419-
1420- ```python
1421- from __future__ import absolute_import
1422- from __future__ import division
1423- from __future__ import print_function
1424- ```
1425-
14261429For more information read the
14271430[Python future statement definitions](https:// docs.python.org/ 3 / library/ __future__ .html)
14281431documentation.
@@ -1433,19 +1436,7 @@ feature a specific future import enables in your code today, keeping it in place
14331436in the file prevents later modifications of the code from inadvertently
14341437depending on the older behavior.
14351438
1436- Use other `from __future__ ` import statements as you see fit. We did not include
1437- `unicode_literals` in our recommendations for 2.7 as it was not a clear win due
1438- to implicit default codec conversion consequences it introduced in many places
1439- within 2.7 . Most dual- version 2 - and - 3 code was better off with explicit use of
1440- `b ' ' ` and `u ' ' ` bytes and unicode string literals where necessary.
1441-
1442- # #### The six, future, and past libraries
1443-
1444- When your project still needs to support use under both Python 2 and 3 , use the
1445- [six](https:// pypi.org/ project/ six/ ),
1446- [future](https:// pypi.org/ project/ future/ ), and
1447- [past](https:// pypi.org/ project/ past/ ) libraries as you see fit. They exist to
1448- make your code cleaner and life easier.
1439+ Use other `from __future__ ` import statements as you see fit.
14491440
14501441< a id = " s2.21-type-annotated-code" >< / a>
14511442< a id = " s2.21-typed-code" >< / a>
@@ -1455,11 +1446,10 @@ make your code cleaner and life easier.
14551446< a id = " typed-code" >< / a>
14561447# ## 2.21 Type Annotated Code
14571448
1458- You can annotate Python 3 code with type hints according to
1449+ You can annotate Python code with type hints according to
14591450[PEP - 484 ](https:// www.python.org/ dev/ peps/ pep- 0484 / ), and type - check the code at
14601451build time with a type checking tool like [pytype](https:// github.com/ google/ pytype).
14611452
1462-
14631453Type annotations can be in the source or in a
14641454[stub pyi file ](https:// www.python.org/ dev/ peps/ pep- 0484 / # stub-files). Whenever
14651455possible, annotations should be in the source. Use pyi files for third- party or
@@ -2129,8 +2119,8 @@ If your class has public attributes, they should be documented here in an
21292119class SampleClass:
21302120 """ Summary of class here.
21312121
2132- Longer class information... .
2133- Longer class information... .
2122+ Longer class information...
2123+ Longer class information...
21342124
21352125 Attributes:
21362126 likes_spam: A boolean indicating if we like SPAM or not .
@@ -2146,6 +2136,34 @@ class SampleClass:
21462136 """ Performs operation blah."""
21472137```
21482138
2139+ All class docstrings should start with a one-line summary that describes what
2140+ the class instance represents. This implies that subclasses of `Exception`
2141+ should also describe what the exception represents, and not the context in which
2142+ it might occur. The class docstring should not repeat unnecessary information,
2143+ such as that the class is a class.
2144+
2145+ ```python
2146+ class CheeseShopAddress:
2147+ """ The address of a cheese shop.
2148+
2149+ ...
2150+ """
2151+
2152+ class OutOfCheeseError(Exception):
2153+ """ No more cheese is available."""
2154+ ```
2155+
2156+ ```python
2157+ class CheeseShopAddress:
2158+ """ Class that describes the address of a cheese shop.
2159+
2160+ ...
2161+ """
2162+
2163+ class OutOfCheeseError(Exception):
2164+ """ Raised when no more cheese is available."""
2165+ ```
2166+
21492167<a id="s3.8.5-block-and-inline-comments"></a>
21502168<a id="comments-in-block-and-inline"></a>
21512169<a id="s3.8.5-comments-in-block-and-inline"></a>
@@ -2542,9 +2560,7 @@ grouped from most generic to least generic:
254225601 . Python future import statements. For example:
25432561
25442562 ```python
2545- from __future__ import absolute_import
2546- from __future__ import division
2547- from __future__ import print_function
2563+ from __future__ import annotations
25482564 ```
25492565
25502566 See [above](# from-future-imports) for more information about those.
@@ -2945,13 +2961,23 @@ the function into smaller and more manageable pieces.
29452961
29462962* Familiarize yourself with
29472963 [PEP - 484 ](https:// www.python.org/ dev/ peps/ pep- 0484 / ).
2964+
29482965* In methods, only annotate `self ` , or `cls ` if it is necessary for proper
2949- type information. e.g., `@ classmethod def create(cls : Type[T]) -> T: return
2950- cls ()`
2966+ type information. e.g.,
2967+
2968+ ```python
2969+ @ classmethod
2970+ def create(cls : Type[T]) -> T:
2971+ return cls ()
2972+ ```
2973+
29512974* Similarly, don' t feel compelled to annotate the return value of `__init__`
29522975 (where `None ` is the only valid option).
2976+
29532977* If any other variable or a returned type should not be expressed, use `Any` .
2978+
29542979* You are not required to annotate all the functions in a module.
2980+
29552981 - At least annotate your public APIs.
29562982 - Use judgment to get to a good balance between safety and clarity on the
29572983 one hand, and flexibility on the other.
@@ -3245,8 +3271,7 @@ def add(a: AddableType, b: AddableType) -> AddableType:
32453271```
32463272
32473273A common predefined type variable in the `typing` module is `AnyStr` . Use it for
3248- multiple annotations that can be `bytes ` or `unicode ` and must all be the same
3249- type .
3274+ multiple annotations that can be `bytes ` or `str ` and must all be the same type .
32503275
32513276```python
32523277from typing import AnyStr
@@ -3283,46 +3308,16 @@ No:
32833308< a id = " typing-strings" >< / a>
32843309# ### 3.19.11 String types
32853310
3286- The proper type for annotating strings depends on what versions of Python the
3287- code is intended for .
3311+ > Do not use `typing.Text` in new code. It' s only for Python 2/3 compatibility.
32883312
3289- Prefer to use `str ` , though `Text` is also acceptable. Be consistent in using
3290- one or the other. For code that deals with binary data, use `bytes ` . For Python
3291- 2 compatible code that processes text data (`str ` or `unicode ` in Python 2 ,
3292- `str ` in Python 3 ), use `Text` .
3313+ Use `str ` for string/ text data. For code that deals with binary data, use
3314+ `bytes ` .
32933315
32943316```python
3295- def deals_with_text_data_in_py3 (x: str ) -> str :
3317+ def deals_with_text_data (x: str ) -> str :
32963318 ...
32973319def deals_with_binary_data(x: bytes ) -> bytes :
32983320 ...
3299- def py2_compatible_text_data_processor(x: Text) -> Text:
3300- ...
3301- ```
3302-
3303- In some uncommon Python 2 compatibility cases, `str ` may make sense instead of
3304- `Text` , typically to aid compatibility when the return types aren' t the same
3305- between Python 2 and Python 3 . Never use `unicode ` as it doesn' t exist in Python
3306- 3 . The reason this discrepancy exists is because `str ` means something different
3307- in Python 2 than in Python 3 .
3308-
3309- No:
3310-
3311- ```python
3312- def py2_code(x: str ) -> unicode :
3313- ...
3314- ```
3315-
3316- If the type can be either bytes or text, use `Union` , with the appropriate text
3317- type .
3318-
3319- ```python
3320- from typing import Text, Union
3321- ...
3322- def py3_only(x: Union[bytes , str ]) -> Union[bytes , str ]:
3323- ...
3324- def py2_compatible(x: Union[bytes , Text]) -> Union[bytes , Text]:
3325- ...
33263321```
33273322
33283323If all the string types of a function are always the same, for example if the
@@ -3336,11 +3331,11 @@ return type is the same as the argument type in the code above, use
33363331< a id = " typing-imports" >< / a>
33373332# ### 3.19.12 Imports For Typing
33383333
3339- For classes from the `typing` and `collections.abc` modules for use in
3340- annotations , always import the class itself. This keeps common annotations more
3341- concise and matches typing practices used around the world. You are explicitly
3342- allowed to import multiple specific classes on one line from the `typing` and
3343- `collections.abc` modules. Ex:
3334+ For symbols from the `typing` and `collections.abc` modules used to support
3335+ static analysis and type checking , always import the symbol itself. This keeps
3336+ common annotations more concise and matches typing practices used around the
3337+ world. You are explicitly allowed to import multiple specific classes on one
3338+ line from the `typing` and `collections.abc` modules. Ex:
33443339
33453340```python
33463341from collections.abc import Mapping, Sequence
0 commit comments