Skip to content

Commit 6271f3f

Browse files
Google Python teamgpshead
authored andcommitted
Project import generated by Copybara.
PiperOrigin-RevId: 224224079
1 parent fdc20e8 commit 6271f3f

File tree

1 file changed

+68
-61
lines changed

1 file changed

+68
-61
lines changed

pyguide.md

Lines changed: 68 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,9 @@ last does not enforce that the arguments are actually unused.
106106
<a id="imports"></a>
107107
### 2.2 Imports
108108

109-
Use `import`s for packages and modules only, not for individual classes or
110-
functions. Note that there is an explicit exemption for imports from the
111-
[typing module](#typing-imports).
109+
Use `import` statements for packages and modules only, not for individual
110+
classes or functions. Note that there is an explicit exemption for imports from
111+
the [typing module](#typing-imports).
112112

113113
<a id="s2.2.1-definition"></a>
114114
#### 2.2.1 Definition
@@ -509,20 +509,23 @@ means a dictionary). This is also an advantage.
509509
Use default iterators and operators for types that support them, like lists,
510510
dictionaries, and files. The built-in types define iterator methods, too. Prefer
511511
these methods to methods that return lists, except that you should not mutate a
512-
container while iterating over it.
512+
container while iterating over it. Never use Python 2 specific iteration
513+
methods such as `dict.iter*()` unless necessary.
513514
514515
```python
515516
Yes: for key in adict: ...
516517
if key not in adict: ...
517518
if obj in alist: ...
518519
for line in afile: ...
519-
for k, v in dict.iteritems(): ...
520+
for k, v in adict.items(): ...
521+
for k, v in six.iteritems(adict): ...
520522
```
521523
522524
```python
523525
No: for key in adict.keys(): ...
524526
if not adict.has_key(key): ...
525527
for line in afile.readlines(): ...
528+
for k, v in dict.iteritems(): ...
526529
```
527530
528531
<a id="s2.9-generators"></a>
@@ -584,9 +587,9 @@ function may only contain an expression.
584587
<a id="s2.10.4-decision"></a>
585588
#### 2.10.4 Decision
586589
587-
Okay to use them for one-liners. If the code inside the lambda function is any
588-
longer than 60-80 chars, it's probably better to define it as a regular (nested)
589-
function.
590+
Okay to use them for one-liners. If the code inside the lambda function is
591+
longer than 60-80 chars, it's probably better to define it as a regular [nested
592+
function](#lexical-scoping).
590593
591594
For common operations like multiplication, use the functions from the `operator`
592595
module instead of lambda functions. For example, prefer `operator.mul` to
@@ -1084,7 +1087,7 @@ use it yet, all code should be written to be 3 compatible (and tested under
10841087
#### 2.20.1 Definition
10851088
10861089
Python 3 is a significant change in the Python language. While existing code is
1087-
often written with 2.7 in mind there are some simple things to do to make code
1090+
often written with 2.7 in mind, there are some simple things to do to make code
10881091
more explicit about its intentions and thus better prepared for use under Python
10891092
3 without modification.
10901093
@@ -1197,7 +1200,7 @@ This highly depends on the complexity of your project. Give it a try.
11971200
<a id="semicolons"></a>
11981201
### 3.1 Semicolons
11991202
1200-
Do not terminate your lines with semi-colons and do not use semi-colons to put
1203+
Do not terminate your lines with semicolons, and do not use semicolons to put
12011204
two statements on the same line.
12021205
12031206
<a id="s3.2-line-length"></a>
@@ -1430,7 +1433,7 @@ No: spam( ham[ 1 ], { eggs: 2 }, [ ] )
14301433
```
14311434
14321435
No whitespace before a comma, semicolon, or colon. Do use whitespace after a
1433-
comma, semicolon, or colon except at the end of the line.
1436+
comma, semicolon, or colon, except at the end of the line.
14341437
14351438
```python
14361439
Yes: if x == 4:
@@ -1477,10 +1480,10 @@ Yes: x == 1
14771480
No: x<1
14781481
```
14791482
1480-
Never use spaces around the '=' sign when passing keyword arguments.
1481-
Only use spaces around the '=' sign defining a default parameter value
1482-
[when a type annotation is present](#typing-default-values),
1483-
do not use spaces around '=' for default parameter values otherwise.
1483+
Never use spaces around `=` when passing keyword arguments or defining a default
1484+
parameter value, with one exception: [when a type annotation is
1485+
present](#typing-default-values), _do_ use spaces around the `=` for the default
1486+
parameter value.
14841487
14851488
```python
14861489
Yes: def complex(real, imag=0.0): return Magic(r=real, i=imag)
@@ -1543,7 +1546,7 @@ inline comments.
15431546
<a id="comments-in-doc-strings"></a>
15441547
#### 3.8.1 Docstrings
15451548
1546-
Python uses docstrings for commenting code. A doc string is a string that is the
1549+
Python uses _docstrings_ to document code. A docstring is a string that is the
15471550
first statement in a package, module, class or function. These strings can be
15481551
extracted automatically through the `__doc__` member of the object and are used
15491552
by `pydoc`.
@@ -1568,8 +1571,7 @@ LGPL, GPL)
15681571
<a id="functions-and-methods"></a>
15691572
#### 3.8.3 Functions and Methods
15701573
1571-
As used in this section "function" applies to methods, functions, and
1572-
generators.
1574+
In this section, "function" means a method, function, or generator.
15731575
15741576
A function must have a docstring, unless it meets all of the following criteria:
15751577
@@ -1585,13 +1587,13 @@ function's calling syntax and its semantics, not its implementation. For tricky
15851587
code, comments alongside the code are more appropriate than using docstrings.
15861588
15871589
A method that overrides a method from a base class may have a simple docstring
1588-
sending the reader to its overridden method's docstring, such as
1589-
`"""See base class."""`. The rationale is that there is no need to repeat in
1590-
many places documentation that is already present in the base method's
1591-
docstring. However, if the overriding method's behavior is substantially
1592-
different than that of the overridden method or details need to be provided
1593-
about it (e.g., documenting additional side-effects), a docstring is required on
1594-
the overriding method, with at least those differences.
1590+
sending the reader to its overridden method's docstring, such as `"""See base
1591+
class."""`. The rationale is that there is no need to repeat in many places
1592+
documentation that is already present in the base method's docstring. However,
1593+
if the overriding method's behavior is substantially different from the
1594+
overridden method, or details need to be provided (e.g., documenting additional
1595+
side effects), a docstring with at least those differences is required on the
1596+
overriding method.
15951597
15961598
Certain aspects of a function should be documented in special sections, listed
15971599
below. Each section begins with a heading line, which ends with a colon.
@@ -1764,9 +1766,9 @@ No: class SampleClass:
17641766
pass
17651767
```
17661768
1767-
Inheriting from `object` is needed to make properties work properly in Python 2,
1768-
and can protect your code from some potential incompatibility with Python 3. It
1769-
also defines special methods that implement the default semantics of objects
1769+
Inheriting from `object` is needed to make properties work properly in Python 2
1770+
and can protect your code from potential incompatibility with Python 3. It also
1771+
defines special methods that implement the default semantics of objects
17701772
including `__new__`, `__init__`, `__delattr__`, `__getattribute__`,
17711773
`__setattr__`, `__hash__`, `__repr__`, and `__str__`.
17721774
@@ -1860,28 +1862,28 @@ Don't do this.
18601862
Explicitly close files and sockets when done with them.
18611863
18621864
Leaving files, sockets or other file-like objects open unnecessarily has many
1863-
downsides, including:
1865+
downsides:
18641866
18651867
- They may consume limited system resources, such as file descriptors. Code
18661868
that deals with many such objects may exhaust those resources unnecessarily
18671869
if they're not returned to the system promptly after use.
1868-
- Holding files open may prevent other actions being performed on them, such
1869-
as moves or deletion.
1870+
- Holding files open may prevent other actions such as moving or deleting
1871+
them.
18701872
- Files and sockets that are shared throughout a program may inadvertently be
18711873
read from or written to after logically being closed. If they are actually
18721874
closed, attempts to read or write from them will throw exceptions, making
18731875
the problem known sooner.
18741876
18751877
Furthermore, while files and sockets are automatically closed when the file
1876-
object is destructed, tying the life-time of the file object to the state of the
1877-
file is poor practice, for several reasons:
1878+
object is destructed, tying the lifetime of the file object to the state of the
1879+
file is poor practice:
18781880
18791881
- There are no guarantees as to when the runtime will actually run the file's
18801882
destructor. Different Python implementations use different memory management
18811883
techniques, such as delayed Garbage Collection, which may increase the
18821884
object's lifetime arbitrarily and indefinitely.
1883-
- Unexpected references to the file may keep it around longer than intended
1884-
(e.g. in tracebacks of exceptions, inside globals, etc).
1885+
- Unexpected references to the file, e.g. in globals or exception tracebacks,
1886+
may keep it around longer than intended.
18851887
18861888
The preferred way to manage files is using the ["with"
18871889
statement](http://docs.python.org/reference/compound_stmts.html#the-with-statement):
@@ -1910,13 +1912,16 @@ with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
19101912
Use `TODO` comments for code that is temporary, a short-term solution, or
19111913
good-enough but not perfect.
19121914
1913-
`TODO`s should include the string `TODO` in all caps, followed by the
1915+
A `TODO` comment begins with the string `TODO` in all caps and a parenthesized
19141916
name, e-mail address, or other identifier
1915-
of the person or issue with the best context about the problem referenced by the
1916-
`TODO`, in parentheses. A comment explaining what there is to do is required.
1917-
The main purpose is to have a consistent `TODO` format that can be searched to
1918-
find out how to get more details upon request. A `TODO` is not a commitment that
1919-
the person referenced will fix the problem. Thus when you create a `TODO`, it is almost always your name that is given.
1917+
of the person or issue with the best context about the problem. This is followed
1918+
by an explanation of what there is to do.
1919+
1920+
The purpose is to have a consistent `TODO` format that can be searched to find
1921+
out how to get more details. A `TODO` is not a commitment that the person
1922+
referenced will fix the problem. Thus when you create a
1923+
`TODO`, it is almost always your name
1924+
that is given.
19201925
19211926
```python
19221927
# TODO([email protected]): Use a "*" here for string repetition.
@@ -1947,7 +1952,7 @@ No: import os, sys
19471952
19481953
Imports are always put at the top of the file, just after any module comments
19491954
and docstrings and before module globals and constants. Imports should be
1950-
grouped with the order being most generic to least generic:
1955+
grouped from most generic to least generic:
19511956
19521957
1. Python standard library imports. For example:
19531958
@@ -2049,10 +2054,10 @@ No:
20492054
<a id="access-control"></a>
20502055
### 3.15 Access Control
20512056
2052-
If an accessor function would be trivial you should use public variables instead
2053-
of accessor functions to avoid the extra cost of function calls in Python. When
2054-
more functionality is added you can use `property` to keep the syntax
2055-
consistent.
2057+
If an accessor function would be trivial, you should use public variables
2058+
instead of accessor functions to avoid the extra cost of function calls in
2059+
Python. When more functionality is added you can use `property` to keep the
2060+
syntax consistent.
20562061
20572062
On the other hand, if access is more complex, or the cost of accessing the
20582063
variable is significant, you should use function calls (following the
@@ -2098,7 +2103,7 @@ Always use a `.py` filename extension. Never use dashes.
20982103
<a id="naming-conventions"></a>
20992104
#### 3.16.2 Naming Convention
21002105
2101-
- "Internal" means internal to a module or protected or private within a
2106+
- "Internal" means internal to a module, or protected or private within a
21022107
class.
21032108
21042109
- Prepending a single underscore (`_`) has some support for protecting module
@@ -2115,8 +2120,8 @@ Always use a `.py` filename extension. Never use dashes.
21152120
- Use CapWords for class names, but lower\_with\_under.py for module names.
21162121
Although there are some old modules named CapWords.py, this is now
21172122
discouraged because it's confusing when the module happens to be named after
2118-
a class. ("wait -- did I write `import StringIO` or
2119-
`from StringIO import StringIO`?")
2123+
a class. ("wait -- did I write `import StringIO` or `from StringIO import
2124+
StringIO`?")
21202125
21212126
- Underscores may appear in *unittest* method names starting with `test` to
21222127
separate logical components of the name, even if those components use
@@ -2215,9 +2220,9 @@ containing `exec "$0.py" "$@"`.
22152220
</table>
22162221
22172222
While Python supports making things private by using a leading double underscore
2218-
`__` (aka. "dunder") prefix on a name their use is discouraged. Prefer the use
2219-
of a single underscore. They are much easier to type, read, and to access from
2220-
small unittests. Lint warnings take care of invalid access to protected members.
2223+
`__` (aka. "dunder") prefix on a name, this is discouraged. Prefer the use of a
2224+
single underscore. They are easier to type, read, and to access from small
2225+
unittests. Lint warnings take care of invalid access to protected members.
22212226
22222227
22232228
<a id="s3.17-main"></a>
@@ -2400,10 +2405,10 @@ class MyClass(object):
24002405
<a id="typing-default-values"></a>
24012406
#### 3.19.4 Default Values
24022407
2403-
As per [PEP-008](https://www.python.org/dev/peps/pep-0008/#other-recommendations)
2404-
when combining an argument annotation with a default value, use spaces around
2405-
the = sign (but only for those arguments that have both an annotation and a
2406-
default).
2408+
As per
2409+
[PEP-008](https://www.python.org/dev/peps/pep-0008/#other-recommendations), use
2410+
spaces around the `=` _only_ for arguments that have both a type annotation and
2411+
a default value.
24072412
24082413
```python
24092414
Yes:
@@ -2540,7 +2545,8 @@ def check_length(x: AnyStr) -> AnyStr:
25402545
25412546
<a id="s3.19.11-strings"></a>
25422547
<a id="typing-strings"></a>
2543-
#### 3.19.11 Strings types
2548+
2549+
#### 3.19.11 String types
25442550
25452551
The proper type for annotating strings depends on what versions of Python the
25462552
code is intended for.
@@ -2626,10 +2632,10 @@ from typing import Any as AnyType
26262632
<a id="typing-conditional-imports"></a>
26272633
#### 3.19.13 Conditional Imports
26282634
2629-
Use conditional imports only in exceptional cases, when the additional imports
2630-
needed for type checking must be avoided at runtime. This pattern is discouraged
2631-
and alternatives such as refactoring the code to allow top level imports should
2632-
be preferred.
2635+
Use conditional imports only in exceptional cases where the additional imports
2636+
needed for type checking must be avoided at runtime. This pattern is
2637+
discouraged; alternatives such as refactoring the code to allow top level
2638+
imports should be preferred.
26332639
26342640
Imports that are needed only for type annotations can be placed within an
26352641
`if TYPE_CHECKING:` block.
@@ -2729,3 +2735,4 @@ style is also important. If code you add to a file looks drastically different
27292735
from the existing code around it, it throws readers out of their rhythm when
27302736
they go to read it. Avoid this.
27312737
2738+

0 commit comments

Comments
 (0)