1517 lines
117 KiB
HTML
1517 lines
117 KiB
HTML
|
||
<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<meta name="color-scheme" content="light dark">
|
||
<title>PEP 8 – Style Guide for Python Code | peps.python.org</title>
|
||
<link rel="shortcut icon" href="../_static/py.png">
|
||
<link rel="canonical" href="https://peps.python.org/pep-0008/">
|
||
<link rel="stylesheet" href="../_static/style.css" type="text/css">
|
||
<link rel="stylesheet" href="../_static/mq.css" type="text/css">
|
||
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" media="(prefers-color-scheme: light)" id="pyg-light">
|
||
<link rel="stylesheet" href="../_static/pygments_dark.css" type="text/css" media="(prefers-color-scheme: dark)" id="pyg-dark">
|
||
<link rel="alternate" type="application/rss+xml" title="Latest PEPs" href="https://peps.python.org/peps.rss">
|
||
<meta property="og:title" content='PEP 8 – Style Guide for Python Code | peps.python.org'>
|
||
<meta property="og:description" content="This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python.">
|
||
<meta property="og:type" content="website">
|
||
<meta property="og:url" content="https://peps.python.org/pep-0008/">
|
||
<meta property="og:site_name" content="Python Enhancement Proposals (PEPs)">
|
||
<meta property="og:image" content="https://peps.python.org/_static/og-image.png">
|
||
<meta property="og:image:alt" content="Python PEPs">
|
||
<meta property="og:image:width" content="200">
|
||
<meta property="og:image:height" content="200">
|
||
<meta name="description" content="This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python.">
|
||
<meta name="theme-color" content="#3776ab">
|
||
</head>
|
||
<body>
|
||
|
||
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
|
||
<symbol id="svg-sun-half" viewBox="0 0 24 24" pointer-events="all">
|
||
<title>Following system colour scheme</title>
|
||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
|
||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||
<circle cx="12" cy="12" r="9"></circle>
|
||
<path d="M12 3v18m0-12l4.65-4.65M12 14.3l7.37-7.37M12 19.6l8.85-8.85"></path>
|
||
</svg>
|
||
</symbol>
|
||
<symbol id="svg-moon" viewBox="0 0 24 24" pointer-events="all">
|
||
<title>Selected dark colour scheme</title>
|
||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
|
||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
|
||
<path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454z"></path>
|
||
</svg>
|
||
</symbol>
|
||
<symbol id="svg-sun" viewBox="0 0 24 24" pointer-events="all">
|
||
<title>Selected light colour scheme</title>
|
||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
|
||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||
<circle cx="12" cy="12" r="5"></circle>
|
||
<line x1="12" y1="1" x2="12" y2="3"></line>
|
||
<line x1="12" y1="21" x2="12" y2="23"></line>
|
||
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
|
||
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
|
||
<line x1="1" y1="12" x2="3" y2="12"></line>
|
||
<line x1="21" y1="12" x2="23" y2="12"></line>
|
||
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
|
||
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
|
||
</svg>
|
||
</symbol>
|
||
</svg>
|
||
<script>
|
||
|
||
document.documentElement.dataset.colour_scheme = localStorage.getItem("colour_scheme") || "auto"
|
||
</script>
|
||
<section id="pep-page-section">
|
||
<header>
|
||
<h1>Python Enhancement Proposals</h1>
|
||
<ul class="breadcrumbs">
|
||
<li><a href="https://www.python.org/" title="The Python Programming Language">Python</a> » </li>
|
||
<li><a href="../pep-0000/">PEP Index</a> » </li>
|
||
<li>PEP 8</li>
|
||
</ul>
|
||
<button id="colour-scheme-cycler" onClick="setColourScheme(nextColourScheme())">
|
||
<svg aria-hidden="true" class="colour-scheme-icon-when-auto"><use href="#svg-sun-half"></use></svg>
|
||
<svg aria-hidden="true" class="colour-scheme-icon-when-dark"><use href="#svg-moon"></use></svg>
|
||
<svg aria-hidden="true" class="colour-scheme-icon-when-light"><use href="#svg-sun"></use></svg>
|
||
<span class="visually-hidden">Toggle light / dark / auto colour theme</span>
|
||
</button>
|
||
</header>
|
||
<article>
|
||
<section id="pep-content">
|
||
<h1 class="page-title">PEP 8 – Style Guide for Python Code</h1>
|
||
<dl class="rfc2822 field-list simple">
|
||
<dt class="field-odd">Author<span class="colon">:</span></dt>
|
||
<dd class="field-odd">Guido van Rossum <guido at python.org>,
|
||
Barry Warsaw <barry at python.org>,
|
||
Alyssa Coghlan <ncoghlan at gmail.com></dd>
|
||
<dt class="field-even">Status<span class="colon">:</span></dt>
|
||
<dd class="field-even"><abbr title="Currently valid informational guidance, or an in-use process">Active</abbr></dd>
|
||
<dt class="field-odd">Type<span class="colon">:</span></dt>
|
||
<dd class="field-odd"><abbr title="Normative PEP describing or proposing a change to a Python community process, workflow or governance">Process</abbr></dd>
|
||
<dt class="field-even">Created<span class="colon">:</span></dt>
|
||
<dd class="field-even">05-Jul-2001</dd>
|
||
<dt class="field-odd">Post-History<span class="colon">:</span></dt>
|
||
<dd class="field-odd">05-Jul-2001, 01-Aug-2013</dd>
|
||
</dl>
|
||
<hr class="docutils" />
|
||
<section id="contents">
|
||
<details><summary>Table of Contents</summary><ul class="simple">
|
||
<li><a class="reference internal" href="#introduction">Introduction</a></li>
|
||
<li><a class="reference internal" href="#a-foolish-consistency-is-the-hobgoblin-of-little-minds">A Foolish Consistency is the Hobgoblin of Little Minds</a></li>
|
||
<li><a class="reference internal" href="#code-lay-out">Code Lay-out</a><ul>
|
||
<li><a class="reference internal" href="#indentation">Indentation</a></li>
|
||
<li><a class="reference internal" href="#tabs-or-spaces">Tabs or Spaces?</a></li>
|
||
<li><a class="reference internal" href="#maximum-line-length">Maximum Line Length</a></li>
|
||
<li><a class="reference internal" href="#should-a-line-break-before-or-after-a-binary-operator">Should a Line Break Before or After a Binary Operator?</a></li>
|
||
<li><a class="reference internal" href="#blank-lines">Blank Lines</a></li>
|
||
<li><a class="reference internal" href="#source-file-encoding">Source File Encoding</a></li>
|
||
<li><a class="reference internal" href="#imports">Imports</a></li>
|
||
<li><a class="reference internal" href="#module-level-dunder-names">Module Level Dunder Names</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#string-quotes">String Quotes</a></li>
|
||
<li><a class="reference internal" href="#whitespace-in-expressions-and-statements">Whitespace in Expressions and Statements</a><ul>
|
||
<li><a class="reference internal" href="#pet-peeves">Pet Peeves</a></li>
|
||
<li><a class="reference internal" href="#other-recommendations">Other Recommendations</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#when-to-use-trailing-commas">When to Use Trailing Commas</a></li>
|
||
<li><a class="reference internal" href="#comments">Comments</a><ul>
|
||
<li><a class="reference internal" href="#block-comments">Block Comments</a></li>
|
||
<li><a class="reference internal" href="#inline-comments">Inline Comments</a></li>
|
||
<li><a class="reference internal" href="#documentation-strings">Documentation Strings</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#naming-conventions">Naming Conventions</a><ul>
|
||
<li><a class="reference internal" href="#overriding-principle">Overriding Principle</a></li>
|
||
<li><a class="reference internal" href="#descriptive-naming-styles">Descriptive: Naming Styles</a></li>
|
||
<li><a class="reference internal" href="#prescriptive-naming-conventions">Prescriptive: Naming Conventions</a><ul>
|
||
<li><a class="reference internal" href="#names-to-avoid">Names to Avoid</a></li>
|
||
<li><a class="reference internal" href="#ascii-compatibility">ASCII Compatibility</a></li>
|
||
<li><a class="reference internal" href="#package-and-module-names">Package and Module Names</a></li>
|
||
<li><a class="reference internal" href="#class-names">Class Names</a></li>
|
||
<li><a class="reference internal" href="#type-variable-names">Type Variable Names</a></li>
|
||
<li><a class="reference internal" href="#exception-names">Exception Names</a></li>
|
||
<li><a class="reference internal" href="#global-variable-names">Global Variable Names</a></li>
|
||
<li><a class="reference internal" href="#function-and-variable-names">Function and Variable Names</a></li>
|
||
<li><a class="reference internal" href="#function-and-method-arguments">Function and Method Arguments</a></li>
|
||
<li><a class="reference internal" href="#method-names-and-instance-variables">Method Names and Instance Variables</a></li>
|
||
<li><a class="reference internal" href="#constants">Constants</a></li>
|
||
<li><a class="reference internal" href="#designing-for-inheritance">Designing for Inheritance</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#public-and-internal-interfaces">Public and Internal Interfaces</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#programming-recommendations">Programming Recommendations</a><ul>
|
||
<li><a class="reference internal" href="#function-annotations">Function Annotations</a></li>
|
||
<li><a class="reference internal" href="#variable-annotations">Variable Annotations</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#references">References</a></li>
|
||
<li><a class="reference internal" href="#copyright">Copyright</a></li>
|
||
</ul>
|
||
</details></section>
|
||
<section id="introduction">
|
||
<h2><a class="toc-backref" href="#introduction" role="doc-backlink">Introduction</a></h2>
|
||
<p>This document gives coding conventions for the Python code comprising
|
||
the standard library in the main Python distribution. Please see the
|
||
companion informational PEP describing <a class="pep reference internal" href="../pep-0007/" title="PEP 7 – Style Guide for C Code">style guidelines for the C code
|
||
in the C implementation of Python</a>.</p>
|
||
<p>This document and <a class="pep reference internal" href="../pep-0257/" title="PEP 257 – Docstring Conventions">PEP 257</a> (Docstring Conventions) were adapted from
|
||
Guido’s original Python Style Guide essay, with some additions from
|
||
Barry’s style guide <a class="footnote-reference brackets" href="#id6" id="id1">[2]</a>.</p>
|
||
<p>This style guide evolves over time as additional conventions are
|
||
identified and past conventions are rendered obsolete by changes in
|
||
the language itself.</p>
|
||
<p>Many projects have their own coding style guidelines. In the event of any
|
||
conflicts, such project-specific guides take precedence for that project.</p>
|
||
</section>
|
||
<section id="a-foolish-consistency-is-the-hobgoblin-of-little-minds">
|
||
<h2><a class="toc-backref" href="#a-foolish-consistency-is-the-hobgoblin-of-little-minds" role="doc-backlink">A Foolish Consistency is the Hobgoblin of Little Minds</a></h2>
|
||
<p>One of Guido’s key insights is that code is read much more often than
|
||
it is written. The guidelines provided here are intended to improve
|
||
the readability of code and make it consistent across the wide
|
||
spectrum of Python code. As <a class="pep reference internal" href="../pep-0020/" title="PEP 20 – The Zen of Python">PEP 20</a> says, “Readability counts”.</p>
|
||
<p>A style guide is about consistency. Consistency with this style guide
|
||
is important. Consistency within a project is more important.
|
||
Consistency within one module or function is the most important.</p>
|
||
<p>However, know when to be inconsistent – sometimes style guide
|
||
recommendations just aren’t applicable. When in doubt, use your best
|
||
judgment. Look at other examples and decide what looks best. And
|
||
don’t hesitate to ask!</p>
|
||
<p>In particular: do not break backwards compatibility just to comply with
|
||
this PEP!</p>
|
||
<p>Some other good reasons to ignore a particular guideline:</p>
|
||
<ol class="arabic simple">
|
||
<li>When applying the guideline would make the code less readable, even
|
||
for someone who is used to reading code that follows this PEP.</li>
|
||
<li>To be consistent with surrounding code that also breaks it (maybe
|
||
for historic reasons) – although this is also an opportunity to
|
||
clean up someone else’s mess (in true XP style).</li>
|
||
<li>Because the code in question predates the introduction of the
|
||
guideline and there is no other reason to be modifying that code.</li>
|
||
<li>When the code needs to remain compatible with older versions of
|
||
Python that don’t support the feature recommended by the style guide.</li>
|
||
</ol>
|
||
</section>
|
||
<section id="code-lay-out">
|
||
<h2><a class="toc-backref" href="#code-lay-out" role="doc-backlink">Code Lay-out</a></h2>
|
||
<section id="indentation">
|
||
<h3><a class="toc-backref" href="#indentation" role="doc-backlink">Indentation</a></h3>
|
||
<p>Use 4 spaces per indentation level.</p>
|
||
<p>Continuation lines should align wrapped elements either vertically
|
||
using Python’s implicit line joining inside parentheses, brackets and
|
||
braces, or using a <em>hanging indent</em> <a class="footnote-reference brackets" href="#fn-hi" id="id2">[1]</a>. When using a hanging
|
||
indent the following should be considered; there should be no
|
||
arguments on the first line and further indentation should be used to
|
||
clearly distinguish itself as a continuation line:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
|
||
<span class="c1"># Aligned with opening delimiter.</span>
|
||
<span class="n">foo</span> <span class="o">=</span> <span class="n">long_function_name</span><span class="p">(</span><span class="n">var_one</span><span class="p">,</span> <span class="n">var_two</span><span class="p">,</span>
|
||
<span class="n">var_three</span><span class="p">,</span> <span class="n">var_four</span><span class="p">)</span>
|
||
|
||
<span class="c1"># Add 4 spaces (an extra level of indentation) to distinguish arguments from the rest.</span>
|
||
<span class="k">def</span> <span class="nf">long_function_name</span><span class="p">(</span>
|
||
<span class="n">var_one</span><span class="p">,</span> <span class="n">var_two</span><span class="p">,</span> <span class="n">var_three</span><span class="p">,</span>
|
||
<span class="n">var_four</span><span class="p">):</span>
|
||
<span class="nb">print</span><span class="p">(</span><span class="n">var_one</span><span class="p">)</span>
|
||
|
||
<span class="c1"># Hanging indents should add a level.</span>
|
||
<span class="n">foo</span> <span class="o">=</span> <span class="n">long_function_name</span><span class="p">(</span>
|
||
<span class="n">var_one</span><span class="p">,</span> <span class="n">var_two</span><span class="p">,</span>
|
||
<span class="n">var_three</span><span class="p">,</span> <span class="n">var_four</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
|
||
<span class="c1"># Arguments on first line forbidden when not using vertical alignment.</span>
|
||
<span class="n">foo</span> <span class="o">=</span> <span class="n">long_function_name</span><span class="p">(</span><span class="n">var_one</span><span class="p">,</span> <span class="n">var_two</span><span class="p">,</span>
|
||
<span class="n">var_three</span><span class="p">,</span> <span class="n">var_four</span><span class="p">)</span>
|
||
|
||
<span class="c1"># Further indentation required as indentation is not distinguishable.</span>
|
||
<span class="k">def</span> <span class="nf">long_function_name</span><span class="p">(</span>
|
||
<span class="n">var_one</span><span class="p">,</span> <span class="n">var_two</span><span class="p">,</span> <span class="n">var_three</span><span class="p">,</span>
|
||
<span class="n">var_four</span><span class="p">):</span>
|
||
<span class="nb">print</span><span class="p">(</span><span class="n">var_one</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The 4-space rule is optional for continuation lines.</p>
|
||
<p>Optional:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Hanging indents *may* be indented to other than 4 spaces.</span>
|
||
<span class="n">foo</span> <span class="o">=</span> <span class="n">long_function_name</span><span class="p">(</span>
|
||
<span class="n">var_one</span><span class="p">,</span> <span class="n">var_two</span><span class="p">,</span>
|
||
<span class="n">var_three</span><span class="p">,</span> <span class="n">var_four</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p id="multiline-if-statements">When the conditional part of an <code class="docutils literal notranslate"><span class="pre">if</span></code>-statement is long enough to require
|
||
that it be written across multiple lines, it’s worth noting that the
|
||
combination of a two character keyword (i.e. <code class="docutils literal notranslate"><span class="pre">if</span></code>), plus a single space,
|
||
plus an opening parenthesis creates a natural 4-space indent for the
|
||
subsequent lines of the multiline conditional. This can produce a visual
|
||
conflict with the indented suite of code nested inside the <code class="docutils literal notranslate"><span class="pre">if</span></code>-statement,
|
||
which would also naturally be indented to 4 spaces. This PEP takes no
|
||
explicit position on how (or whether) to further visually distinguish such
|
||
conditional lines from the nested suite inside the <code class="docutils literal notranslate"><span class="pre">if</span></code>-statement.
|
||
Acceptable options in this situation include, but are not limited to:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># No extra indentation.</span>
|
||
<span class="k">if</span> <span class="p">(</span><span class="n">this_is_one_thing</span> <span class="ow">and</span>
|
||
<span class="n">that_is_another_thing</span><span class="p">):</span>
|
||
<span class="n">do_something</span><span class="p">()</span>
|
||
|
||
<span class="c1"># Add a comment, which will provide some distinction in editors</span>
|
||
<span class="c1"># supporting syntax highlighting.</span>
|
||
<span class="k">if</span> <span class="p">(</span><span class="n">this_is_one_thing</span> <span class="ow">and</span>
|
||
<span class="n">that_is_another_thing</span><span class="p">):</span>
|
||
<span class="c1"># Since both conditions are true, we can frobnicate.</span>
|
||
<span class="n">do_something</span><span class="p">()</span>
|
||
|
||
<span class="c1"># Add some extra indentation on the conditional continuation line.</span>
|
||
<span class="k">if</span> <span class="p">(</span><span class="n">this_is_one_thing</span>
|
||
<span class="ow">and</span> <span class="n">that_is_another_thing</span><span class="p">):</span>
|
||
<span class="n">do_something</span><span class="p">()</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>(Also see the discussion of whether to break before or after binary
|
||
operators below.)</p>
|
||
<p>The closing brace/bracket/parenthesis on multiline constructs may
|
||
either line up under the first non-whitespace character of the last
|
||
line of list, as in:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">my_list</span> <span class="o">=</span> <span class="p">[</span>
|
||
<span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span>
|
||
<span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span>
|
||
<span class="p">]</span>
|
||
<span class="n">result</span> <span class="o">=</span> <span class="n">some_function_that_takes_arguments</span><span class="p">(</span>
|
||
<span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span>
|
||
<span class="s1">'d'</span><span class="p">,</span> <span class="s1">'e'</span><span class="p">,</span> <span class="s1">'f'</span><span class="p">,</span>
|
||
<span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>or it may be lined up under the first character of the line that
|
||
starts the multiline construct, as in:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">my_list</span> <span class="o">=</span> <span class="p">[</span>
|
||
<span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span>
|
||
<span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span>
|
||
<span class="p">]</span>
|
||
<span class="n">result</span> <span class="o">=</span> <span class="n">some_function_that_takes_arguments</span><span class="p">(</span>
|
||
<span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span>
|
||
<span class="s1">'d'</span><span class="p">,</span> <span class="s1">'e'</span><span class="p">,</span> <span class="s1">'f'</span><span class="p">,</span>
|
||
<span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
</section>
|
||
<section id="tabs-or-spaces">
|
||
<h3><a class="toc-backref" href="#tabs-or-spaces" role="doc-backlink">Tabs or Spaces?</a></h3>
|
||
<p>Spaces are the preferred indentation method.</p>
|
||
<p>Tabs should be used solely to remain consistent with code that is
|
||
already indented with tabs.</p>
|
||
<p>Python disallows mixing tabs and spaces for indentation.</p>
|
||
</section>
|
||
<section id="maximum-line-length">
|
||
<h3><a class="toc-backref" href="#maximum-line-length" role="doc-backlink">Maximum Line Length</a></h3>
|
||
<p>Limit all lines to a maximum of 79 characters.</p>
|
||
<p>For flowing long blocks of text with fewer structural restrictions
|
||
(docstrings or comments), the line length should be limited to 72
|
||
characters.</p>
|
||
<p>Limiting the required editor window width makes it possible to have
|
||
several files open side by side, and works well when using code
|
||
review tools that present the two versions in adjacent columns.</p>
|
||
<p>The default wrapping in most tools disrupts the visual structure of the
|
||
code, making it more difficult to understand. The limits are chosen to
|
||
avoid wrapping in editors with the window width set to 80, even
|
||
if the tool places a marker glyph in the final column when wrapping
|
||
lines. Some web based tools may not offer dynamic line wrapping at all.</p>
|
||
<p>Some teams strongly prefer a longer line length. For code maintained
|
||
exclusively or primarily by a team that can reach agreement on this
|
||
issue, it is okay to increase the line length limit up to 99 characters,
|
||
provided that comments and docstrings are still wrapped at 72
|
||
characters.</p>
|
||
<p>The Python standard library is conservative and requires limiting
|
||
lines to 79 characters (and docstrings/comments to 72).</p>
|
||
<p>The preferred way of wrapping long lines is by using Python’s implied
|
||
line continuation inside parentheses, brackets and braces. Long lines
|
||
can be broken over multiple lines by wrapping expressions in
|
||
parentheses. These should be used in preference to using a backslash
|
||
for line continuation.</p>
|
||
<p>Backslashes may still be appropriate at times. For example, long,
|
||
multiple <code class="docutils literal notranslate"><span class="pre">with</span></code>-statements could not use implicit continuation
|
||
before Python 3.10, so backslashes were acceptable for that case:</p>
|
||
<div class="maybe highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'/path/to/some/file/you/want/to/read'</span><span class="p">)</span> <span class="k">as</span> <span class="n">file_1</span><span class="p">,</span> \
|
||
<span class="nb">open</span><span class="p">(</span><span class="s1">'/path/to/some/file/being/written'</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">)</span> <span class="k">as</span> <span class="n">file_2</span><span class="p">:</span>
|
||
<span class="n">file_2</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">file_1</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>(See the previous discussion on <a class="reference internal" href="#multiline-if-statements">multiline if-statements</a> for further
|
||
thoughts on the indentation of such multiline <code class="docutils literal notranslate"><span class="pre">with</span></code>-statements.)</p>
|
||
<p>Another such case is with <code class="docutils literal notranslate"><span class="pre">assert</span></code> statements.</p>
|
||
<p>Make sure to indent the continued line appropriately.</p>
|
||
</section>
|
||
<section id="should-a-line-break-before-or-after-a-binary-operator">
|
||
<span id="pep8-operator-linebreak"></span><h3><a class="toc-backref" href="#should-a-line-break-before-or-after-a-binary-operator" role="doc-backlink">Should a Line Break Before or After a Binary Operator?</a></h3>
|
||
<p>For decades the recommended style was to break after binary operators.
|
||
But this can hurt readability in two ways: the operators tend to get
|
||
scattered across different columns on the screen, and each operator is
|
||
moved away from its operand and onto the previous line. Here, the eye
|
||
has to do extra work to tell which items are added and which are
|
||
subtracted:</p>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="c1"># operators sit far away from their operands</span>
|
||
<span class="n">income</span> <span class="o">=</span> <span class="p">(</span><span class="n">gross_wages</span> <span class="o">+</span>
|
||
<span class="n">taxable_interest</span> <span class="o">+</span>
|
||
<span class="p">(</span><span class="n">dividends</span> <span class="o">-</span> <span class="n">qualified_dividends</span><span class="p">)</span> <span class="o">-</span>
|
||
<span class="n">ira_deduction</span> <span class="o">-</span>
|
||
<span class="n">student_loan_interest</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>To solve this readability problem, mathematicians and their publishers
|
||
follow the opposite convention. Donald Knuth explains the traditional
|
||
rule in his <em>Computers and Typesetting</em> series: “Although formulas
|
||
within a paragraph always break after binary operations and relations,
|
||
displayed formulas always break before binary operations” <a class="footnote-reference brackets" href="#id7" id="id3">[3]</a>.</p>
|
||
<p>Following the tradition from mathematics usually results in more
|
||
readable code:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="c1"># easy to match operators with operands</span>
|
||
<span class="n">income</span> <span class="o">=</span> <span class="p">(</span><span class="n">gross_wages</span>
|
||
<span class="o">+</span> <span class="n">taxable_interest</span>
|
||
<span class="o">+</span> <span class="p">(</span><span class="n">dividends</span> <span class="o">-</span> <span class="n">qualified_dividends</span><span class="p">)</span>
|
||
<span class="o">-</span> <span class="n">ira_deduction</span>
|
||
<span class="o">-</span> <span class="n">student_loan_interest</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>In Python code, it is permissible to break before or after a binary
|
||
operator, as long as the convention is consistent locally. For new
|
||
code Knuth’s style is suggested.</p>
|
||
</section>
|
||
<section id="blank-lines">
|
||
<h3><a class="toc-backref" href="#blank-lines" role="doc-backlink">Blank Lines</a></h3>
|
||
<p>Surround top-level function and class definitions with two blank
|
||
lines.</p>
|
||
<p>Method definitions inside a class are surrounded by a single blank
|
||
line.</p>
|
||
<p>Extra blank lines may be used (sparingly) to separate groups of
|
||
related functions. Blank lines may be omitted between a bunch of
|
||
related one-liners (e.g. a set of dummy implementations).</p>
|
||
<p>Use blank lines in functions, sparingly, to indicate logical sections.</p>
|
||
<p>Python accepts the control-L (i.e. ^L) form feed character as
|
||
whitespace; many tools treat these characters as page separators, so
|
||
you may use them to separate pages of related sections of your file.
|
||
Note, some editors and web-based code viewers may not recognize
|
||
control-L as a form feed and will show another glyph in its place.</p>
|
||
</section>
|
||
<section id="source-file-encoding">
|
||
<h3><a class="toc-backref" href="#source-file-encoding" role="doc-backlink">Source File Encoding</a></h3>
|
||
<p>Code in the core Python distribution should always use UTF-8, and should not
|
||
have an encoding declaration.</p>
|
||
<p>In the standard library, non-UTF-8 encodings should be used only for
|
||
test purposes. Use non-ASCII characters sparingly, preferably only to
|
||
denote places and human names. If using non-ASCII characters as data,
|
||
avoid noisy Unicode characters like z̯̯͡a̧͎̺l̡͓̫g̹̲o̡̼̘ and byte order
|
||
marks.</p>
|
||
<p>All identifiers in the Python standard library MUST use ASCII-only
|
||
identifiers, and SHOULD use English words wherever feasible (in many
|
||
cases, abbreviations and technical terms are used which aren’t
|
||
English).</p>
|
||
<p>Open source projects with a global audience are encouraged to adopt a
|
||
similar policy.</p>
|
||
</section>
|
||
<section id="imports">
|
||
<h3><a class="toc-backref" href="#imports" role="doc-backlink">Imports</a></h3>
|
||
<ul>
|
||
<li>Imports should usually be on separate lines:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="kn">import</span> <span class="nn">os</span>
|
||
<span class="kn">import</span> <span class="nn">sys</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">os</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>It’s okay to say this though:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="kn">from</span> <span class="nn">subprocess</span> <span class="kn">import</span> <span class="n">Popen</span><span class="p">,</span> <span class="n">PIPE</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Imports are always put at the top of the file, just after any module
|
||
comments and docstrings, and before module globals and constants.<p>Imports should be grouped in the following order:</p>
|
||
<ol class="arabic simple">
|
||
<li>Standard library imports.</li>
|
||
<li>Related third party imports.</li>
|
||
<li>Local application/library specific imports.</li>
|
||
</ol>
|
||
<p>You should put a blank line between each group of imports.</p>
|
||
</li>
|
||
<li>Absolute imports are recommended, as they are usually more readable
|
||
and tend to be better behaved (or at least give better error
|
||
messages) if the import system is incorrectly configured (such as
|
||
when a directory inside a package ends up on <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>):<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">mypkg.sibling</span>
|
||
<span class="kn">from</span> <span class="nn">mypkg</span> <span class="kn">import</span> <span class="n">sibling</span>
|
||
<span class="kn">from</span> <span class="nn">mypkg.sibling</span> <span class="kn">import</span> <span class="n">example</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>However, explicit relative imports are an acceptable alternative to
|
||
absolute imports, especially when dealing with complex package layouts
|
||
where using absolute imports would be unnecessarily verbose:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">sibling</span>
|
||
<span class="kn">from</span> <span class="nn">.sibling</span> <span class="kn">import</span> <span class="n">example</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Standard library code should avoid complex package layouts and always
|
||
use absolute imports.</p>
|
||
</li>
|
||
<li>When importing a class from a class-containing module, it’s usually
|
||
okay to spell this:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">myclass</span> <span class="kn">import</span> <span class="n">MyClass</span>
|
||
<span class="kn">from</span> <span class="nn">foo.bar.yourclass</span> <span class="kn">import</span> <span class="n">YourClass</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>If this spelling causes local name clashes, then spell them explicitly:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">myclass</span>
|
||
<span class="kn">import</span> <span class="nn">foo.bar.yourclass</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>and use <code class="docutils literal notranslate"><span class="pre">myclass.MyClass</span></code> and <code class="docutils literal notranslate"><span class="pre">foo.bar.yourclass.YourClass</span></code>.</p>
|
||
</li>
|
||
<li>Wildcard imports (<code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre"><module></span> <span class="pre">import</span> <span class="pre">*</span></code>) should be avoided, as
|
||
they make it unclear which names are present in the namespace,
|
||
confusing both readers and many automated tools. There is one
|
||
defensible use case for a wildcard import, which is to republish an
|
||
internal interface as part of a public API (for example, overwriting
|
||
a pure Python implementation of an interface with the definitions
|
||
from an optional accelerator module and exactly which definitions
|
||
will be overwritten isn’t known in advance).<p>When republishing names this way, the guidelines below regarding
|
||
public and internal interfaces still apply.</p>
|
||
</li>
|
||
</ul>
|
||
</section>
|
||
<section id="module-level-dunder-names">
|
||
<h3><a class="toc-backref" href="#module-level-dunder-names" role="doc-backlink">Module Level Dunder Names</a></h3>
|
||
<p>Module level “dunders” (i.e. names with two leading and two trailing
|
||
underscores) such as <code class="docutils literal notranslate"><span class="pre">__all__</span></code>, <code class="docutils literal notranslate"><span class="pre">__author__</span></code>, <code class="docutils literal notranslate"><span class="pre">__version__</span></code>,
|
||
etc. should be placed after the module docstring but before any import
|
||
statements <em>except</em> <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span></code> imports. Python mandates that
|
||
future-imports must appear in the module before any other code except
|
||
docstrings:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="sd">"""This is the example module.</span>
|
||
|
||
<span class="sd">This module does stuff.</span>
|
||
<span class="sd">"""</span>
|
||
|
||
<span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">barry_as_FLUFL</span>
|
||
|
||
<span class="n">__all__</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">]</span>
|
||
<span class="n">__version__</span> <span class="o">=</span> <span class="s1">'0.1'</span>
|
||
<span class="n">__author__</span> <span class="o">=</span> <span class="s1">'Cardinal Biggles'</span>
|
||
|
||
<span class="kn">import</span> <span class="nn">os</span>
|
||
<span class="kn">import</span> <span class="nn">sys</span>
|
||
</pre></div>
|
||
</div>
|
||
</section>
|
||
</section>
|
||
<section id="string-quotes">
|
||
<h2><a class="toc-backref" href="#string-quotes" role="doc-backlink">String Quotes</a></h2>
|
||
<p>In Python, single-quoted strings and double-quoted strings are the
|
||
same. This PEP does not make a recommendation for this. Pick a rule
|
||
and stick to it. When a string contains single or double quote
|
||
characters, however, use the other one to avoid backslashes in the
|
||
string. It improves readability.</p>
|
||
<p>For triple-quoted strings, always use double quote characters to be
|
||
consistent with the docstring convention in <a class="pep reference internal" href="../pep-0257/" title="PEP 257 – Docstring Conventions">PEP 257</a>.</p>
|
||
</section>
|
||
<section id="whitespace-in-expressions-and-statements">
|
||
<h2><a class="toc-backref" href="#whitespace-in-expressions-and-statements" role="doc-backlink">Whitespace in Expressions and Statements</a></h2>
|
||
<section id="pet-peeves">
|
||
<h3><a class="toc-backref" href="#pet-peeves" role="doc-backlink">Pet Peeves</a></h3>
|
||
<p>Avoid extraneous whitespace in the following situations:</p>
|
||
<ul>
|
||
<li>Immediately inside parentheses, brackets or braces:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="n">spam</span><span class="p">(</span><span class="n">ham</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="p">{</span><span class="n">eggs</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="n">spam</span><span class="p">(</span> <span class="n">ham</span><span class="p">[</span> <span class="mi">1</span> <span class="p">],</span> <span class="p">{</span> <span class="n">eggs</span><span class="p">:</span> <span class="mi">2</span> <span class="p">}</span> <span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Between a trailing comma and a following close parenthesis:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="n">foo</span> <span class="o">=</span> <span class="p">(</span><span class="mi">0</span><span class="p">,)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="n">bar</span> <span class="o">=</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Immediately before a comma, semicolon, or colon:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">if</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">4</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">);</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">y</span><span class="p">,</span> <span class="n">x</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">if</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">4</span> <span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span> <span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="p">;</span> <span class="n">x</span> <span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">y</span> <span class="p">,</span> <span class="n">x</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>However, in a slice the colon acts like a binary operator, and
|
||
should have equal amounts on either side (treating it as the
|
||
operator with the lowest priority). In an extended slice, both
|
||
colons must have the same amount of spacing applied. Exception:
|
||
when a slice parameter is omitted, the space is omitted:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="n">ham</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">9</span><span class="p">],</span> <span class="n">ham</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">9</span><span class="p">:</span><span class="mi">3</span><span class="p">],</span> <span class="n">ham</span><span class="p">[:</span><span class="mi">9</span><span class="p">:</span><span class="mi">3</span><span class="p">],</span> <span class="n">ham</span><span class="p">[</span><span class="mi">1</span><span class="p">::</span><span class="mi">3</span><span class="p">],</span> <span class="n">ham</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">9</span><span class="p">:]</span>
|
||
<span class="n">ham</span><span class="p">[</span><span class="n">lower</span><span class="p">:</span><span class="n">upper</span><span class="p">],</span> <span class="n">ham</span><span class="p">[</span><span class="n">lower</span><span class="p">:</span><span class="n">upper</span><span class="p">:],</span> <span class="n">ham</span><span class="p">[</span><span class="n">lower</span><span class="p">::</span><span class="n">step</span><span class="p">]</span>
|
||
<span class="n">ham</span><span class="p">[</span><span class="n">lower</span><span class="o">+</span><span class="n">offset</span> <span class="p">:</span> <span class="n">upper</span><span class="o">+</span><span class="n">offset</span><span class="p">]</span>
|
||
<span class="n">ham</span><span class="p">[:</span> <span class="n">upper_fn</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="p">:</span> <span class="n">step_fn</span><span class="p">(</span><span class="n">x</span><span class="p">)],</span> <span class="n">ham</span><span class="p">[::</span> <span class="n">step_fn</span><span class="p">(</span><span class="n">x</span><span class="p">)]</span>
|
||
<span class="n">ham</span><span class="p">[</span><span class="n">lower</span> <span class="o">+</span> <span class="n">offset</span> <span class="p">:</span> <span class="n">upper</span> <span class="o">+</span> <span class="n">offset</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="n">ham</span><span class="p">[</span><span class="n">lower</span> <span class="o">+</span> <span class="n">offset</span><span class="p">:</span><span class="n">upper</span> <span class="o">+</span> <span class="n">offset</span><span class="p">]</span>
|
||
<span class="n">ham</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span> <span class="mi">9</span><span class="p">],</span> <span class="n">ham</span><span class="p">[</span><span class="mi">1</span> <span class="p">:</span><span class="mi">9</span><span class="p">],</span> <span class="n">ham</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">9</span> <span class="p">:</span><span class="mi">3</span><span class="p">]</span>
|
||
<span class="n">ham</span><span class="p">[</span><span class="n">lower</span> <span class="p">:</span> <span class="p">:</span> <span class="n">step</span><span class="p">]</span>
|
||
<span class="n">ham</span><span class="p">[</span> <span class="p">:</span> <span class="n">upper</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Immediately before the open parenthesis that starts the argument
|
||
list of a function call:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="n">spam</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="n">spam</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Immediately before the open parenthesis that starts an indexing or
|
||
slicing:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="n">dct</span><span class="p">[</span><span class="s1">'key'</span><span class="p">]</span> <span class="o">=</span> <span class="n">lst</span><span class="p">[</span><span class="n">index</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="n">dct</span> <span class="p">[</span><span class="s1">'key'</span><span class="p">]</span> <span class="o">=</span> <span class="n">lst</span> <span class="p">[</span><span class="n">index</span><span class="p">]</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>More than one space around an assignment (or other) operator to
|
||
align it with another:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
|
||
<span class="n">y</span> <span class="o">=</span> <span class="mi">2</span>
|
||
<span class="n">long_variable</span> <span class="o">=</span> <span class="mi">3</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
|
||
<span class="n">y</span> <span class="o">=</span> <span class="mi">2</span>
|
||
<span class="n">long_variable</span> <span class="o">=</span> <span class="mi">3</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</section>
|
||
<section id="other-recommendations">
|
||
<h3><a class="toc-backref" href="#other-recommendations" role="doc-backlink">Other Recommendations</a></h3>
|
||
<ul>
|
||
<li>Avoid trailing whitespace anywhere. Because it’s usually invisible,
|
||
it can be confusing: e.g. a backslash followed by a space and a
|
||
newline does not count as a line continuation marker. Some editors
|
||
don’t preserve it and many projects (like CPython itself) have
|
||
pre-commit hooks that reject it.</li>
|
||
<li>Always surround these binary operators with a single space on either
|
||
side: assignment (<code class="docutils literal notranslate"><span class="pre">=</span></code>), augmented assignment (<code class="docutils literal notranslate"><span class="pre">+=</span></code>, <code class="docutils literal notranslate"><span class="pre">-=</span></code>
|
||
etc.), comparisons (<code class="docutils literal notranslate"><span class="pre">==</span></code>, <code class="docutils literal notranslate"><span class="pre"><</span></code>, <code class="docutils literal notranslate"><span class="pre">></span></code>, <code class="docutils literal notranslate"><span class="pre">!=</span></code>, <code class="docutils literal notranslate"><span class="pre"><></span></code>, <code class="docutils literal notranslate"><span class="pre"><=</span></code>,
|
||
<code class="docutils literal notranslate"><span class="pre">>=</span></code>, <code class="docutils literal notranslate"><span class="pre">in</span></code>, <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code>, <code class="docutils literal notranslate"><span class="pre">is</span></code>, <code class="docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code>), Booleans (<code class="docutils literal notranslate"><span class="pre">and</span></code>,
|
||
<code class="docutils literal notranslate"><span class="pre">or</span></code>, <code class="docutils literal notranslate"><span class="pre">not</span></code>).</li>
|
||
<li>If operators with different priorities are used, consider adding
|
||
whitespace around the operators with the lowest priority(ies). Use
|
||
your own judgment; however, never use more than one space, and
|
||
always have the same amount of whitespace on both sides of a binary
|
||
operator:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="n">i</span> <span class="o">=</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">1</span>
|
||
<span class="n">submitted</span> <span class="o">+=</span> <span class="mi">1</span>
|
||
<span class="n">x</span> <span class="o">=</span> <span class="n">x</span><span class="o">*</span><span class="mi">2</span> <span class="o">-</span> <span class="mi">1</span>
|
||
<span class="n">hypot2</span> <span class="o">=</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span> <span class="o">+</span> <span class="n">y</span><span class="o">*</span><span class="n">y</span>
|
||
<span class="n">c</span> <span class="o">=</span> <span class="p">(</span><span class="n">a</span><span class="o">+</span><span class="n">b</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="n">a</span><span class="o">-</span><span class="n">b</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="n">i</span><span class="o">=</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span>
|
||
<span class="n">submitted</span> <span class="o">+=</span><span class="mi">1</span>
|
||
<span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">-</span> <span class="mi">1</span>
|
||
<span class="n">hypot2</span> <span class="o">=</span> <span class="n">x</span> <span class="o">*</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="o">*</span> <span class="n">y</span>
|
||
<span class="n">c</span> <span class="o">=</span> <span class="p">(</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="n">a</span> <span class="o">-</span> <span class="n">b</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Function annotations should use the normal rules for colons and
|
||
always have spaces around the <code class="docutils literal notranslate"><span class="pre">-></span></code> arrow if present. (See
|
||
<a class="reference internal" href="#function-annotations">Function Annotations</a> below for more about function annotations.):<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">def</span> <span class="nf">munge</span><span class="p">(</span><span class="nb">input</span><span class="p">:</span> <span class="n">AnyStr</span><span class="p">):</span> <span class="o">...</span>
|
||
<span class="k">def</span> <span class="nf">munge</span><span class="p">()</span> <span class="o">-></span> <span class="n">PosInt</span><span class="p">:</span> <span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">def</span> <span class="nf">munge</span><span class="p">(</span><span class="nb">input</span><span class="p">:</span><span class="n">AnyStr</span><span class="p">):</span> <span class="o">...</span>
|
||
<span class="k">def</span> <span class="nf">munge</span><span class="p">()</span><span class="o">-></span><span class="n">PosInt</span><span class="p">:</span> <span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Don’t use spaces around the <code class="docutils literal notranslate"><span class="pre">=</span></code> sign when used to indicate a
|
||
keyword argument, or when used to indicate a default value for an
|
||
<em>unannotated</em> function parameter:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">def</span> <span class="nf">complex</span><span class="p">(</span><span class="n">real</span><span class="p">,</span> <span class="n">imag</span><span class="o">=</span><span class="mf">0.0</span><span class="p">):</span>
|
||
<span class="k">return</span> <span class="n">magic</span><span class="p">(</span><span class="n">r</span><span class="o">=</span><span class="n">real</span><span class="p">,</span> <span class="n">i</span><span class="o">=</span><span class="n">imag</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">def</span> <span class="nf">complex</span><span class="p">(</span><span class="n">real</span><span class="p">,</span> <span class="n">imag</span> <span class="o">=</span> <span class="mf">0.0</span><span class="p">):</span>
|
||
<span class="k">return</span> <span class="n">magic</span><span class="p">(</span><span class="n">r</span> <span class="o">=</span> <span class="n">real</span><span class="p">,</span> <span class="n">i</span> <span class="o">=</span> <span class="n">imag</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>When combining an argument annotation with a default value, however, do use
|
||
spaces around the <code class="docutils literal notranslate"><span class="pre">=</span></code> sign:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">def</span> <span class="nf">munge</span><span class="p">(</span><span class="n">sep</span><span class="p">:</span> <span class="n">AnyStr</span> <span class="o">=</span> <span class="kc">None</span><span class="p">):</span> <span class="o">...</span>
|
||
<span class="k">def</span> <span class="nf">munge</span><span class="p">(</span><span class="nb">input</span><span class="p">:</span> <span class="n">AnyStr</span><span class="p">,</span> <span class="n">sep</span><span class="p">:</span> <span class="n">AnyStr</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">limit</span><span class="o">=</span><span class="mi">1000</span><span class="p">):</span> <span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">def</span> <span class="nf">munge</span><span class="p">(</span><span class="nb">input</span><span class="p">:</span> <span class="n">AnyStr</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="o">...</span>
|
||
<span class="k">def</span> <span class="nf">munge</span><span class="p">(</span><span class="nb">input</span><span class="p">:</span> <span class="n">AnyStr</span><span class="p">,</span> <span class="n">limit</span> <span class="o">=</span> <span class="mi">1000</span><span class="p">):</span> <span class="o">...</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Compound statements (multiple statements on the same line) are
|
||
generally discouraged:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">if</span> <span class="n">foo</span> <span class="o">==</span> <span class="s1">'blah'</span><span class="p">:</span>
|
||
<span class="n">do_blah_thing</span><span class="p">()</span>
|
||
<span class="n">do_one</span><span class="p">()</span>
|
||
<span class="n">do_two</span><span class="p">()</span>
|
||
<span class="n">do_three</span><span class="p">()</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Rather not:</p>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">if</span> <span class="n">foo</span> <span class="o">==</span> <span class="s1">'blah'</span><span class="p">:</span> <span class="n">do_blah_thing</span><span class="p">()</span>
|
||
<span class="n">do_one</span><span class="p">();</span> <span class="n">do_two</span><span class="p">();</span> <span class="n">do_three</span><span class="p">()</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>While sometimes it’s okay to put an if/for/while with a small body
|
||
on the same line, never do this for multi-clause statements. Also
|
||
avoid folding such long lines!<p>Rather not:</p>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">if</span> <span class="n">foo</span> <span class="o">==</span> <span class="s1">'blah'</span><span class="p">:</span> <span class="n">do_blah_thing</span><span class="p">()</span>
|
||
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">lst</span><span class="p">:</span> <span class="n">total</span> <span class="o">+=</span> <span class="n">x</span>
|
||
<span class="k">while</span> <span class="n">t</span> <span class="o"><</span> <span class="mi">10</span><span class="p">:</span> <span class="n">t</span> <span class="o">=</span> <span class="n">delay</span><span class="p">()</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Definitely not:</p>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">if</span> <span class="n">foo</span> <span class="o">==</span> <span class="s1">'blah'</span><span class="p">:</span> <span class="n">do_blah_thing</span><span class="p">()</span>
|
||
<span class="k">else</span><span class="p">:</span> <span class="n">do_non_blah_thing</span><span class="p">()</span>
|
||
|
||
<span class="k">try</span><span class="p">:</span> <span class="n">something</span><span class="p">()</span>
|
||
<span class="k">finally</span><span class="p">:</span> <span class="n">cleanup</span><span class="p">()</span>
|
||
|
||
<span class="n">do_one</span><span class="p">();</span> <span class="n">do_two</span><span class="p">();</span> <span class="n">do_three</span><span class="p">(</span><span class="n">long</span><span class="p">,</span> <span class="n">argument</span><span class="p">,</span>
|
||
<span class="nb">list</span><span class="p">,</span> <span class="n">like</span><span class="p">,</span> <span class="n">this</span><span class="p">)</span>
|
||
|
||
<span class="k">if</span> <span class="n">foo</span> <span class="o">==</span> <span class="s1">'blah'</span><span class="p">:</span> <span class="n">one</span><span class="p">();</span> <span class="n">two</span><span class="p">();</span> <span class="n">three</span><span class="p">()</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</section>
|
||
</section>
|
||
<section id="when-to-use-trailing-commas">
|
||
<h2><a class="toc-backref" href="#when-to-use-trailing-commas" role="doc-backlink">When to Use Trailing Commas</a></h2>
|
||
<p>Trailing commas are usually optional, except they are mandatory when
|
||
making a tuple of one element. For clarity, it is recommended to
|
||
surround the latter in (technically redundant) parentheses:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="n">FILES</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'setup.cfg'</span><span class="p">,)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="n">FILES</span> <span class="o">=</span> <span class="s1">'setup.cfg'</span><span class="p">,</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>When trailing commas are redundant, they are often helpful when a
|
||
version control system is used, when a list of values, arguments or
|
||
imported items is expected to be extended over time. The pattern is
|
||
to put each value (etc.) on a line by itself, always adding a trailing
|
||
comma, and add the close parenthesis/bracket/brace on the next line.
|
||
However it does not make sense to have a trailing comma on the same
|
||
line as the closing delimiter (except in the above case of singleton
|
||
tuples):</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="n">FILES</span> <span class="o">=</span> <span class="p">[</span>
|
||
<span class="s1">'setup.cfg'</span><span class="p">,</span>
|
||
<span class="s1">'tox.ini'</span><span class="p">,</span>
|
||
<span class="p">]</span>
|
||
<span class="n">initialize</span><span class="p">(</span><span class="n">FILES</span><span class="p">,</span>
|
||
<span class="n">error</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
|
||
<span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="n">FILES</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'setup.cfg'</span><span class="p">,</span> <span class="s1">'tox.ini'</span><span class="p">,]</span>
|
||
<span class="n">initialize</span><span class="p">(</span><span class="n">FILES</span><span class="p">,</span> <span class="n">error</span><span class="o">=</span><span class="kc">True</span><span class="p">,)</span>
|
||
</pre></div>
|
||
</div>
|
||
</section>
|
||
<section id="comments">
|
||
<h2><a class="toc-backref" href="#comments" role="doc-backlink">Comments</a></h2>
|
||
<p>Comments that contradict the code are worse than no comments. Always
|
||
make a priority of keeping the comments up-to-date when the code
|
||
changes!</p>
|
||
<p>Comments should be complete sentences. The first word should be
|
||
capitalized, unless it is an identifier that begins with a lower case
|
||
letter (never alter the case of identifiers!).</p>
|
||
<p>Block comments generally consist of one or more paragraphs built out of
|
||
complete sentences, with each sentence ending in a period.</p>
|
||
<p>You should use one or two spaces after a sentence-ending period in
|
||
multi-sentence comments, except after the final sentence.</p>
|
||
<p>Ensure that your comments are clear and easily understandable to other
|
||
speakers of the language you are writing in.</p>
|
||
<p>Python coders from non-English speaking countries: please write your
|
||
comments in English, unless you are 120% sure that the code will never
|
||
be read by people who don’t speak your language.</p>
|
||
<section id="block-comments">
|
||
<h3><a class="toc-backref" href="#block-comments" role="doc-backlink">Block Comments</a></h3>
|
||
<p>Block comments generally apply to some (or all) code that follows
|
||
them, and are indented to the same level as that code. Each line of a
|
||
block comment starts with a <code class="docutils literal notranslate"><span class="pre">#</span></code> and a single space (unless it is
|
||
indented text inside the comment).</p>
|
||
<p>Paragraphs inside a block comment are separated by a line containing a
|
||
single <code class="docutils literal notranslate"><span class="pre">#</span></code>.</p>
|
||
</section>
|
||
<section id="inline-comments">
|
||
<h3><a class="toc-backref" href="#inline-comments" role="doc-backlink">Inline Comments</a></h3>
|
||
<p>Use inline comments sparingly.</p>
|
||
<p>An inline comment is a comment on the same line as a statement.
|
||
Inline comments should be separated by at least two spaces from the
|
||
statement. They should start with a # and a single space.</p>
|
||
<p>Inline comments are unnecessary and in fact distracting if they state
|
||
the obvious. Don’t do this:</p>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># Increment x</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>But sometimes, this is useful:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># Compensate for border</span>
|
||
</pre></div>
|
||
</div>
|
||
</section>
|
||
<section id="documentation-strings">
|
||
<h3><a class="toc-backref" href="#documentation-strings" role="doc-backlink">Documentation Strings</a></h3>
|
||
<p>Conventions for writing good documentation strings
|
||
(a.k.a. “docstrings”) are immortalized in <a class="pep reference internal" href="../pep-0257/" title="PEP 257 – Docstring Conventions">PEP 257</a>.</p>
|
||
<ul>
|
||
<li>Write docstrings for all public modules, functions, classes, and
|
||
methods. Docstrings are not necessary for non-public methods, but
|
||
you should have a comment that describes what the method does. This
|
||
comment should appear after the <code class="docutils literal notranslate"><span class="pre">def</span></code> line.</li>
|
||
<li><a class="pep reference internal" href="../pep-0257/" title="PEP 257 – Docstring Conventions">PEP 257</a> describes good docstring conventions. Note that most
|
||
importantly, the <code class="docutils literal notranslate"><span class="pre">"""</span></code> that ends a multiline docstring should be
|
||
on a line by itself:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="sd">"""Return a foobang</span>
|
||
|
||
<span class="sd">Optional plotz says to frobnicate the bizbaz first.</span>
|
||
<span class="sd">"""</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>For one liner docstrings, please keep the closing <code class="docutils literal notranslate"><span class="pre">"""</span></code> on
|
||
the same line:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="sd">"""Return an ex-parrot."""</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</section>
|
||
</section>
|
||
<section id="naming-conventions">
|
||
<h2><a class="toc-backref" href="#naming-conventions" role="doc-backlink">Naming Conventions</a></h2>
|
||
<p>The naming conventions of Python’s library are a bit of a mess, so
|
||
we’ll never get this completely consistent – nevertheless, here are
|
||
the currently recommended naming standards. New modules and packages
|
||
(including third party frameworks) should be written to these
|
||
standards, but where an existing library has a different style,
|
||
internal consistency is preferred.</p>
|
||
<section id="overriding-principle">
|
||
<h3><a class="toc-backref" href="#overriding-principle" role="doc-backlink">Overriding Principle</a></h3>
|
||
<p>Names that are visible to the user as public parts of the API should
|
||
follow conventions that reflect usage rather than implementation.</p>
|
||
</section>
|
||
<section id="descriptive-naming-styles">
|
||
<h3><a class="toc-backref" href="#descriptive-naming-styles" role="doc-backlink">Descriptive: Naming Styles</a></h3>
|
||
<p>There are a lot of different naming styles. It helps to be able to
|
||
recognize what naming style is being used, independently from what
|
||
they are used for.</p>
|
||
<p>The following naming styles are commonly distinguished:</p>
|
||
<ul>
|
||
<li><code class="docutils literal notranslate"><span class="pre">b</span></code> (single lowercase letter)</li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">B</span></code> (single uppercase letter)</li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">lowercase</span></code></li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">lower_case_with_underscores</span></code></li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">UPPERCASE</span></code></li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">UPPER_CASE_WITH_UNDERSCORES</span></code></li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">CapitalizedWords</span></code> (or CapWords, or CamelCase – so named because
|
||
of the bumpy look of its letters <a class="footnote-reference brackets" href="#id8" id="id4">[4]</a>). This is also sometimes known
|
||
as StudlyCaps.<p>Note: When using acronyms in CapWords, capitalize all the
|
||
letters of the acronym. Thus HTTPServerError is better than
|
||
HttpServerError.</p>
|
||
</li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">mixedCase</span></code> (differs from CapitalizedWords by initial lowercase
|
||
character!)</li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">Capitalized_Words_With_Underscores</span></code> (ugly!)</li>
|
||
</ul>
|
||
<p>There’s also the style of using a short unique prefix to group related
|
||
names together. This is not used much in Python, but it is mentioned
|
||
for completeness. For example, the <code class="docutils literal notranslate"><span class="pre">os.stat()</span></code> function returns a
|
||
tuple whose items traditionally have names like <code class="docutils literal notranslate"><span class="pre">st_mode</span></code>,
|
||
<code class="docutils literal notranslate"><span class="pre">st_size</span></code>, <code class="docutils literal notranslate"><span class="pre">st_mtime</span></code> and so on. (This is done to emphasize the
|
||
correspondence with the fields of the POSIX system call struct, which
|
||
helps programmers familiar with that.)</p>
|
||
<p>The X11 library uses a leading X for all its public functions. In
|
||
Python, this style is generally deemed unnecessary because attribute
|
||
and method names are prefixed with an object, and function names are
|
||
prefixed with a module name.</p>
|
||
<p>In addition, the following special forms using leading or trailing
|
||
underscores are recognized (these can generally be combined with any
|
||
case convention):</p>
|
||
<ul>
|
||
<li><code class="docutils literal notranslate"><span class="pre">_single_leading_underscore</span></code>: weak “internal use” indicator.
|
||
E.g. <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">M</span> <span class="pre">import</span> <span class="pre">*</span></code> does not import objects whose names start
|
||
with an underscore.</li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">single_trailing_underscore_</span></code>: used by convention to avoid
|
||
conflicts with Python keyword, e.g. :<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">tkinter</span><span class="o">.</span><span class="n">Toplevel</span><span class="p">(</span><span class="n">master</span><span class="p">,</span> <span class="n">class_</span><span class="o">=</span><span class="s1">'ClassName'</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">__double_leading_underscore</span></code>: when naming a class attribute,
|
||
invokes name mangling (inside class FooBar, <code class="docutils literal notranslate"><span class="pre">__boo</span></code> becomes
|
||
<code class="docutils literal notranslate"><span class="pre">_FooBar__boo</span></code>; see below).</li>
|
||
<li><code class="docutils literal notranslate"><span class="pre">__double_leading_and_trailing_underscore__</span></code>: “magic” objects or
|
||
attributes that live in user-controlled namespaces.
|
||
E.g. <code class="docutils literal notranslate"><span class="pre">__init__</span></code>, <code class="docutils literal notranslate"><span class="pre">__import__</span></code> or <code class="docutils literal notranslate"><span class="pre">__file__</span></code>. Never invent
|
||
such names; only use them as documented.</li>
|
||
</ul>
|
||
</section>
|
||
<section id="prescriptive-naming-conventions">
|
||
<h3><a class="toc-backref" href="#prescriptive-naming-conventions" role="doc-backlink">Prescriptive: Naming Conventions</a></h3>
|
||
<section id="names-to-avoid">
|
||
<h4><a class="toc-backref" href="#names-to-avoid" role="doc-backlink">Names to Avoid</a></h4>
|
||
<p>Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase
|
||
letter oh), or ‘I’ (uppercase letter eye) as single character variable
|
||
names.</p>
|
||
<p>In some fonts, these characters are indistinguishable from the
|
||
numerals one and zero. When tempted to use ‘l’, use ‘L’ instead.</p>
|
||
</section>
|
||
<section id="ascii-compatibility">
|
||
<h4><a class="toc-backref" href="#ascii-compatibility" role="doc-backlink">ASCII Compatibility</a></h4>
|
||
<p>Identifiers used in the standard library must be ASCII compatible
|
||
as described in the
|
||
<a class="pep reference internal" href="../pep-3131/#policy-specification" title="PEP 3131 – Supporting Non-ASCII Identifiers § Policy Specification">policy section</a>
|
||
of <a class="pep reference internal" href="../pep-3131/" title="PEP 3131 – Supporting Non-ASCII Identifiers">PEP 3131</a>.</p>
|
||
</section>
|
||
<section id="package-and-module-names">
|
||
<h4><a class="toc-backref" href="#package-and-module-names" role="doc-backlink">Package and Module Names</a></h4>
|
||
<p>Modules should have short, all-lowercase names. Underscores can be
|
||
used in the module name if it improves readability. Python packages
|
||
should also have short, all-lowercase names, although the use of
|
||
underscores is discouraged.</p>
|
||
<p>When an extension module written in C or C++ has an accompanying
|
||
Python module that provides a higher level (e.g. more object oriented)
|
||
interface, the C/C++ module has a leading underscore
|
||
(e.g. <code class="docutils literal notranslate"><span class="pre">_socket</span></code>).</p>
|
||
</section>
|
||
<section id="class-names">
|
||
<h4><a class="toc-backref" href="#class-names" role="doc-backlink">Class Names</a></h4>
|
||
<p>Class names should normally use the CapWords convention.</p>
|
||
<p>The naming convention for functions may be used instead in cases where
|
||
the interface is documented and used primarily as a callable.</p>
|
||
<p>Note that there is a separate convention for builtin names: most builtin
|
||
names are single words (or two words run together), with the CapWords
|
||
convention used only for exception names and builtin constants.</p>
|
||
</section>
|
||
<section id="type-variable-names">
|
||
<h4><a class="toc-backref" href="#type-variable-names" role="doc-backlink">Type Variable Names</a></h4>
|
||
<p>Names of type variables introduced in <a class="pep reference internal" href="../pep-0484/" title="PEP 484 – Type Hints">PEP 484</a> should normally use CapWords
|
||
preferring short names: <code class="docutils literal notranslate"><span class="pre">T</span></code>, <code class="docutils literal notranslate"><span class="pre">AnyStr</span></code>, <code class="docutils literal notranslate"><span class="pre">Num</span></code>. It is recommended to add
|
||
suffixes <code class="docutils literal notranslate"><span class="pre">_co</span></code> or <code class="docutils literal notranslate"><span class="pre">_contra</span></code> to the variables used to declare covariant
|
||
or contravariant behavior correspondingly:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">TypeVar</span>
|
||
|
||
<span class="n">VT_co</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'VT_co'</span><span class="p">,</span> <span class="n">covariant</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
|
||
<span class="n">KT_contra</span> <span class="o">=</span> <span class="n">TypeVar</span><span class="p">(</span><span class="s1">'KT_contra'</span><span class="p">,</span> <span class="n">contravariant</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
</section>
|
||
<section id="exception-names">
|
||
<h4><a class="toc-backref" href="#exception-names" role="doc-backlink">Exception Names</a></h4>
|
||
<p>Because exceptions should be classes, the class naming convention
|
||
applies here. However, you should use the suffix “Error” on your
|
||
exception names (if the exception actually is an error).</p>
|
||
</section>
|
||
<section id="global-variable-names">
|
||
<h4><a class="toc-backref" href="#global-variable-names" role="doc-backlink">Global Variable Names</a></h4>
|
||
<p>(Let’s hope that these variables are meant for use inside one module
|
||
only.) The conventions are about the same as those for functions.</p>
|
||
<p>Modules that are designed for use via <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">M</span> <span class="pre">import</span> <span class="pre">*</span></code> should use
|
||
the <code class="docutils literal notranslate"><span class="pre">__all__</span></code> mechanism to prevent exporting globals, or use the
|
||
older convention of prefixing such globals with an underscore (which
|
||
you might want to do to indicate these globals are “module
|
||
non-public”).</p>
|
||
</section>
|
||
<section id="function-and-variable-names">
|
||
<h4><a class="toc-backref" href="#function-and-variable-names" role="doc-backlink">Function and Variable Names</a></h4>
|
||
<p>Function names should be lowercase, with words separated by
|
||
underscores as necessary to improve readability.</p>
|
||
<p>Variable names follow the same convention as function names.</p>
|
||
<p>mixedCase is allowed only in contexts where that’s already the
|
||
prevailing style (e.g. threading.py), to retain backwards
|
||
compatibility.</p>
|
||
</section>
|
||
<section id="function-and-method-arguments">
|
||
<h4><a class="toc-backref" href="#function-and-method-arguments" role="doc-backlink">Function and Method Arguments</a></h4>
|
||
<p>Always use <code class="docutils literal notranslate"><span class="pre">self</span></code> for the first argument to instance methods.</p>
|
||
<p>Always use <code class="docutils literal notranslate"><span class="pre">cls</span></code> for the first argument to class methods.</p>
|
||
<p>If a function argument’s name clashes with a reserved keyword, it is
|
||
generally better to append a single trailing underscore rather than
|
||
use an abbreviation or spelling corruption. Thus <code class="docutils literal notranslate"><span class="pre">class_</span></code> is better
|
||
than <code class="docutils literal notranslate"><span class="pre">clss</span></code>. (Perhaps better is to avoid such clashes by using a
|
||
synonym.)</p>
|
||
</section>
|
||
<section id="method-names-and-instance-variables">
|
||
<h4><a class="toc-backref" href="#method-names-and-instance-variables" role="doc-backlink">Method Names and Instance Variables</a></h4>
|
||
<p>Use the function naming rules: lowercase with words separated by
|
||
underscores as necessary to improve readability.</p>
|
||
<p>Use one leading underscore only for non-public methods and instance
|
||
variables.</p>
|
||
<p>To avoid name clashes with subclasses, use two leading underscores to
|
||
invoke Python’s name mangling rules.</p>
|
||
<p>Python mangles these names with the class name: if class Foo has an
|
||
attribute named <code class="docutils literal notranslate"><span class="pre">__a</span></code>, it cannot be accessed by <code class="docutils literal notranslate"><span class="pre">Foo.__a</span></code>. (An
|
||
insistent user could still gain access by calling <code class="docutils literal notranslate"><span class="pre">Foo._Foo__a</span></code>.)
|
||
Generally, double leading underscores should be used only to avoid
|
||
name conflicts with attributes in classes designed to be subclassed.</p>
|
||
<p>Note: there is some controversy about the use of __names (see below).</p>
|
||
</section>
|
||
<section id="constants">
|
||
<h4><a class="toc-backref" href="#constants" role="doc-backlink">Constants</a></h4>
|
||
<p>Constants are usually defined on a module level and written in all
|
||
capital letters with underscores separating words. Examples include
|
||
<code class="docutils literal notranslate"><span class="pre">MAX_OVERFLOW</span></code> and <code class="docutils literal notranslate"><span class="pre">TOTAL</span></code>.</p>
|
||
</section>
|
||
<section id="designing-for-inheritance">
|
||
<h4><a class="toc-backref" href="#designing-for-inheritance" role="doc-backlink">Designing for Inheritance</a></h4>
|
||
<p>Always decide whether a class’s methods and instance variables
|
||
(collectively: “attributes”) should be public or non-public. If in
|
||
doubt, choose non-public; it’s easier to make it public later than to
|
||
make a public attribute non-public.</p>
|
||
<p>Public attributes are those that you expect unrelated clients of your
|
||
class to use, with your commitment to avoid backwards incompatible
|
||
changes. Non-public attributes are those that are not intended to be
|
||
used by third parties; you make no guarantees that non-public
|
||
attributes won’t change or even be removed.</p>
|
||
<p>We don’t use the term “private” here, since no attribute is really
|
||
private in Python (without a generally unnecessary amount of work).</p>
|
||
<p>Another category of attributes are those that are part of the
|
||
“subclass API” (often called “protected” in other languages). Some
|
||
classes are designed to be inherited from, either to extend or modify
|
||
aspects of the class’s behavior. When designing such a class, take
|
||
care to make explicit decisions about which attributes are public,
|
||
which are part of the subclass API, and which are truly only to be
|
||
used by your base class.</p>
|
||
<p>With this in mind, here are the Pythonic guidelines:</p>
|
||
<ul>
|
||
<li>Public attributes should have no leading underscores.</li>
|
||
<li>If your public attribute name collides with a reserved keyword,
|
||
append a single trailing underscore to your attribute name. This is
|
||
preferable to an abbreviation or corrupted spelling. (However,
|
||
notwithstanding this rule, ‘cls’ is the preferred spelling for any
|
||
variable or argument which is known to be a class, especially the
|
||
first argument to a class method.)<p>Note 1: See the argument name recommendation above for class methods.</p>
|
||
</li>
|
||
<li>For simple public data attributes, it is best to expose just the
|
||
attribute name, without complicated accessor/mutator methods. Keep
|
||
in mind that Python provides an easy path to future enhancement,
|
||
should you find that a simple data attribute needs to grow
|
||
functional behavior. In that case, use properties to hide
|
||
functional implementation behind simple data attribute access
|
||
syntax.<p>Note 1: Try to keep the functional behavior side-effect free,
|
||
although side-effects such as caching are generally fine.</p>
|
||
<p>Note 2: Avoid using properties for computationally expensive
|
||
operations; the attribute notation makes the caller believe that
|
||
access is (relatively) cheap.</p>
|
||
</li>
|
||
<li>If your class is intended to be subclassed, and you have attributes
|
||
that you do not want subclasses to use, consider naming them with
|
||
double leading underscores and no trailing underscores. This
|
||
invokes Python’s name mangling algorithm, where the name of the
|
||
class is mangled into the attribute name. This helps avoid
|
||
attribute name collisions should subclasses inadvertently contain
|
||
attributes with the same name.<p>Note 1: Note that only the simple class name is used in the mangled
|
||
name, so if a subclass chooses both the same class name and attribute
|
||
name, you can still get name collisions.</p>
|
||
<p>Note 2: Name mangling can make certain uses, such as debugging and
|
||
<code class="docutils literal notranslate"><span class="pre">__getattr__()</span></code>, less convenient. However the name mangling
|
||
algorithm is well documented and easy to perform manually.</p>
|
||
<p>Note 3: Not everyone likes name mangling. Try to balance the
|
||
need to avoid accidental name clashes with potential use by
|
||
advanced callers.</p>
|
||
</li>
|
||
</ul>
|
||
</section>
|
||
</section>
|
||
<section id="public-and-internal-interfaces">
|
||
<h3><a class="toc-backref" href="#public-and-internal-interfaces" role="doc-backlink">Public and Internal Interfaces</a></h3>
|
||
<p>Any backwards compatibility guarantees apply only to public interfaces.
|
||
Accordingly, it is important that users be able to clearly distinguish
|
||
between public and internal interfaces.</p>
|
||
<p>Documented interfaces are considered public, unless the documentation
|
||
explicitly declares them to be provisional or internal interfaces exempt
|
||
from the usual backwards compatibility guarantees. All undocumented
|
||
interfaces should be assumed to be internal.</p>
|
||
<p>To better support introspection, modules should explicitly declare the
|
||
names in their public API using the <code class="docutils literal notranslate"><span class="pre">__all__</span></code> attribute. Setting
|
||
<code class="docutils literal notranslate"><span class="pre">__all__</span></code> to an empty list indicates that the module has no public API.</p>
|
||
<p>Even with <code class="docutils literal notranslate"><span class="pre">__all__</span></code> set appropriately, internal interfaces (packages,
|
||
modules, classes, functions, attributes or other names) should still be
|
||
prefixed with a single leading underscore.</p>
|
||
<p>An interface is also considered internal if any containing namespace
|
||
(package, module or class) is considered internal.</p>
|
||
<p>Imported names should always be considered an implementation detail.
|
||
Other modules must not rely on indirect access to such imported names
|
||
unless they are an explicitly documented part of the containing module’s
|
||
API, such as <code class="docutils literal notranslate"><span class="pre">os.path</span></code> or a package’s <code class="docutils literal notranslate"><span class="pre">__init__</span></code> module that exposes
|
||
functionality from submodules.</p>
|
||
</section>
|
||
</section>
|
||
<section id="programming-recommendations">
|
||
<h2><a class="toc-backref" href="#programming-recommendations" role="doc-backlink">Programming Recommendations</a></h2>
|
||
<ul>
|
||
<li>Code should be written in a way that does not disadvantage other
|
||
implementations of Python (PyPy, Jython, IronPython, Cython, Psyco,
|
||
and such).<p>For example, do not rely on CPython’s efficient implementation of
|
||
in-place string concatenation for statements in the form <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+=</span> <span class="pre">b</span></code>
|
||
or <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">a</span> <span class="pre">+</span> <span class="pre">b</span></code>. This optimization is fragile even in CPython (it
|
||
only works for some types) and isn’t present at all in implementations
|
||
that don’t use refcounting. In performance sensitive parts of the
|
||
library, the <code class="docutils literal notranslate"><span class="pre">''.join()</span></code> form should be used instead. This will
|
||
ensure that concatenation occurs in linear time across various
|
||
implementations.</p>
|
||
</li>
|
||
<li>Comparisons to singletons like None should always be done with
|
||
<code class="docutils literal notranslate"><span class="pre">is</span></code> or <code class="docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code>, never the equality operators.<p>Also, beware of writing <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">x</span></code> when you really mean <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">x</span> <span class="pre">is</span> <span class="pre">not</span>
|
||
<span class="pre">None</span></code> – e.g. when testing whether a variable or argument that
|
||
defaults to None was set to some other value. The other value might
|
||
have a type (such as a container) that could be false in a boolean
|
||
context!</p>
|
||
</li>
|
||
<li>Use <code class="docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code> operator rather than <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">...</span> <span class="pre">is</span></code>. While both
|
||
expressions are functionally identical, the former is more readable
|
||
and preferred:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">if</span> <span class="n">foo</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">if</span> <span class="ow">not</span> <span class="n">foo</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>When implementing ordering operations with rich comparisons, it is
|
||
best to implement all six operations (<code class="docutils literal notranslate"><span class="pre">__eq__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ne__</span></code>,
|
||
<code class="docutils literal notranslate"><span class="pre">__lt__</span></code>, <code class="docutils literal notranslate"><span class="pre">__le__</span></code>, <code class="docutils literal notranslate"><span class="pre">__gt__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ge__</span></code>) rather than relying
|
||
on other code to only exercise a particular comparison.<p>To minimize the effort involved, the <code class="docutils literal notranslate"><span class="pre">functools.total_ordering()</span></code>
|
||
decorator provides a tool to generate missing comparison methods.</p>
|
||
<p><a class="pep reference internal" href="../pep-0207/" title="PEP 207 – Rich Comparisons">PEP 207</a> indicates that reflexivity rules <em>are</em> assumed by Python.
|
||
Thus, the interpreter may swap <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">></span> <span class="pre">x</span></code> with <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><</span> <span class="pre">y</span></code>, <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">>=</span> <span class="pre">x</span></code>
|
||
with <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre"><=</span> <span class="pre">y</span></code>, and may swap the arguments of <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">!=</span>
|
||
<span class="pre">y</span></code>. The <code class="docutils literal notranslate"><span class="pre">sort()</span></code> and <code class="docutils literal notranslate"><span class="pre">min()</span></code> operations are guaranteed to use
|
||
the <code class="docutils literal notranslate"><span class="pre"><</span></code> operator and the <code class="docutils literal notranslate"><span class="pre">max()</span></code> function uses the <code class="docutils literal notranslate"><span class="pre">></span></code>
|
||
operator. However, it is best to implement all six operations so
|
||
that confusion doesn’t arise in other contexts.</p>
|
||
</li>
|
||
<li>Always use a def statement instead of an assignment statement that binds
|
||
a lambda expression directly to an identifier:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span> <span class="k">return</span> <span class="mi">2</span><span class="o">*</span><span class="n">x</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="n">f</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="mi">2</span><span class="o">*</span><span class="n">x</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The first form means that the name of the resulting function object is
|
||
specifically ‘f’ instead of the generic ‘<lambda>’. This is more
|
||
useful for tracebacks and string representations in general. The use
|
||
of the assignment statement eliminates the sole benefit a lambda
|
||
expression can offer over an explicit def statement (i.e. that it can
|
||
be embedded inside a larger expression)</p>
|
||
</li>
|
||
<li>Derive exceptions from <code class="docutils literal notranslate"><span class="pre">Exception</span></code> rather than <code class="docutils literal notranslate"><span class="pre">BaseException</span></code>.
|
||
Direct inheritance from <code class="docutils literal notranslate"><span class="pre">BaseException</span></code> is reserved for exceptions
|
||
where catching them is almost always the wrong thing to do.<p>Design exception hierarchies based on the distinctions that code
|
||
<em>catching</em> the exceptions is likely to need, rather than the locations
|
||
where the exceptions are raised. Aim to answer the question
|
||
“What went wrong?” programmatically, rather than only stating that
|
||
“A problem occurred” (see <a class="pep reference internal" href="../pep-3151/" title="PEP 3151 – Reworking the OS and IO exception hierarchy">PEP 3151</a> for an example of this lesson being
|
||
learned for the builtin exception hierarchy)</p>
|
||
<p>Class naming conventions apply here, although you should add the
|
||
suffix “Error” to your exception classes if the exception is an
|
||
error. Non-error exceptions that are used for non-local flow control
|
||
or other forms of signaling need no special suffix.</p>
|
||
</li>
|
||
<li>Use exception chaining appropriately. <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">X</span> <span class="pre">from</span> <span class="pre">Y</span></code>
|
||
should be used to indicate explicit replacement without losing the
|
||
original traceback.<p>When deliberately replacing an inner exception (using <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">X</span> <span class="pre">from</span>
|
||
<span class="pre">None</span></code>), ensure that relevant details are transferred to the new
|
||
exception (such as preserving the attribute name when converting
|
||
KeyError to AttributeError, or embedding the text of the original
|
||
exception in the new exception message).</p>
|
||
</li>
|
||
<li>When catching exceptions, mention specific exceptions whenever
|
||
possible instead of using a bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> clause:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
|
||
<span class="kn">import</span> <span class="nn">platform_specific_module</span>
|
||
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
|
||
<span class="n">platform_specific_module</span> <span class="o">=</span> <span class="kc">None</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>A bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> clause will catch SystemExit and
|
||
KeyboardInterrupt exceptions, making it harder to interrupt a
|
||
program with Control-C, and can disguise other problems. If you
|
||
want to catch all exceptions that signal program errors, use
|
||
<code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">Exception:</span></code> (bare except is equivalent to <code class="docutils literal notranslate"><span class="pre">except</span>
|
||
<span class="pre">BaseException:</span></code>).</p>
|
||
<p>A good rule of thumb is to limit use of bare ‘except’ clauses to two
|
||
cases:</p>
|
||
<ol class="arabic simple">
|
||
<li>If the exception handler will be printing out or logging the
|
||
traceback; at least the user will be aware that an error has
|
||
occurred.</li>
|
||
<li>If the code needs to do some cleanup work, but then lets the
|
||
exception propagate upwards with <code class="docutils literal notranslate"><span class="pre">raise</span></code>. <code class="docutils literal notranslate"><span class="pre">try...finally</span></code>
|
||
can be a better way to handle this case.</li>
|
||
</ol>
|
||
</li>
|
||
<li>When catching operating system errors, prefer the explicit exception
|
||
hierarchy introduced in Python 3.3 over introspection of <code class="docutils literal notranslate"><span class="pre">errno</span></code>
|
||
values.</li>
|
||
<li>Additionally, for all try/except clauses, limit the <code class="docutils literal notranslate"><span class="pre">try</span></code> clause
|
||
to the absolute minimum amount of code necessary. Again, this
|
||
avoids masking bugs:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">try</span><span class="p">:</span>
|
||
<span class="n">value</span> <span class="o">=</span> <span class="n">collection</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
|
||
<span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">key_not_found</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
|
||
<span class="k">else</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">handle_value</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">try</span><span class="p">:</span>
|
||
<span class="c1"># Too broad!</span>
|
||
<span class="k">return</span> <span class="n">handle_value</span><span class="p">(</span><span class="n">collection</span><span class="p">[</span><span class="n">key</span><span class="p">])</span>
|
||
<span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
|
||
<span class="c1"># Will also catch KeyError raised by handle_value()</span>
|
||
<span class="k">return</span> <span class="n">key_not_found</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>When a resource is local to a particular section of code, use a
|
||
<code class="docutils literal notranslate"><span class="pre">with</span></code> statement to ensure it is cleaned up promptly and reliably
|
||
after use. A try/finally statement is also acceptable.</li>
|
||
<li>Context managers should be invoked through separate functions or methods
|
||
whenever they do something other than acquire and release resources:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">with</span> <span class="n">conn</span><span class="o">.</span><span class="n">begin_transaction</span><span class="p">():</span>
|
||
<span class="n">do_stuff_in_transaction</span><span class="p">(</span><span class="n">conn</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">with</span> <span class="n">conn</span><span class="p">:</span>
|
||
<span class="n">do_stuff_in_transaction</span><span class="p">(</span><span class="n">conn</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>The latter example doesn’t provide any information to indicate that
|
||
the <code class="docutils literal notranslate"><span class="pre">__enter__</span></code> and <code class="docutils literal notranslate"><span class="pre">__exit__</span></code> methods are doing something other
|
||
than closing the connection after a transaction. Being explicit is
|
||
important in this case.</p>
|
||
</li>
|
||
<li>Be consistent in return statements. Either all return statements in
|
||
a function should return an expression, or none of them should. If
|
||
any return statement returns an expression, any return statements
|
||
where no value is returned should explicitly state this as <code class="docutils literal notranslate"><span class="pre">return</span>
|
||
<span class="pre">None</span></code>, and an explicit return statement should be present at the
|
||
end of the function (if reachable):<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
|
||
<span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
|
||
<span class="k">if</span> <span class="n">x</span> <span class="o">>=</span> <span class="mi">0</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
|
||
<span class="k">else</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="kc">None</span>
|
||
|
||
<span class="k">def</span> <span class="nf">bar</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
|
||
<span class="k">if</span> <span class="n">x</span> <span class="o"><</span> <span class="mi">0</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="kc">None</span>
|
||
<span class="k">return</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
|
||
<span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
|
||
<span class="k">if</span> <span class="n">x</span> <span class="o">>=</span> <span class="mi">0</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
|
||
|
||
<span class="k">def</span> <span class="nf">bar</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
|
||
<span class="k">if</span> <span class="n">x</span> <span class="o"><</span> <span class="mi">0</span><span class="p">:</span>
|
||
<span class="k">return</span>
|
||
<span class="k">return</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Use <code class="docutils literal notranslate"><span class="pre">''.startswith()</span></code> and <code class="docutils literal notranslate"><span class="pre">''.endswith()</span></code> instead of string
|
||
slicing to check for prefixes or suffixes.<p>startswith() and endswith() are cleaner and less error prone:</p>
|
||
<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">if</span> <span class="n">foo</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">'bar'</span><span class="p">):</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">if</span> <span class="n">foo</span><span class="p">[:</span><span class="mi">3</span><span class="p">]</span> <span class="o">==</span> <span class="s1">'bar'</span><span class="p">:</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Object type comparisons should always use isinstance() instead of
|
||
comparing types directly:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">int</span><span class="p">):</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">if</span> <span class="nb">type</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="ow">is</span> <span class="nb">type</span><span class="p">(</span><span class="mi">1</span><span class="p">):</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>For sequences, (strings, lists, tuples), use the fact that empty
|
||
sequences are false:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">if</span> <span class="ow">not</span> <span class="n">seq</span><span class="p">:</span>
|
||
<span class="k">if</span> <span class="n">seq</span><span class="p">:</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">seq</span><span class="p">):</span>
|
||
<span class="k">if</span> <span class="ow">not</span> <span class="nb">len</span><span class="p">(</span><span class="n">seq</span><span class="p">):</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Don’t write string literals that rely on significant trailing
|
||
whitespace. Such trailing whitespace is visually indistinguishable
|
||
and some editors (or more recently, reindent.py) will trim them.</li>
|
||
<li>Don’t compare boolean values to True or False using <code class="docutils literal notranslate"><span class="pre">==</span></code>:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
<span class="k">if</span> <span class="n">greeting</span><span class="p">:</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">if</span> <span class="n">greeting</span> <span class="o">==</span> <span class="kc">True</span><span class="p">:</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>Worse:</p>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">if</span> <span class="n">greeting</span> <span class="ow">is</span> <span class="kc">True</span><span class="p">:</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Use of the flow control statements <code class="docutils literal notranslate"><span class="pre">return</span></code>/<code class="docutils literal notranslate"><span class="pre">break</span></code>/<code class="docutils literal notranslate"><span class="pre">continue</span></code>
|
||
within the finally suite of a <code class="docutils literal notranslate"><span class="pre">try...finally</span></code>, where the flow control
|
||
statement would jump outside the finally suite, is discouraged. This
|
||
is because such statements will implicitly cancel any active exception
|
||
that is propagating through the finally suite:<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
<span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
|
||
<span class="k">try</span><span class="p">:</span>
|
||
<span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span>
|
||
<span class="k">finally</span><span class="p">:</span>
|
||
<span class="k">return</span> <span class="mi">42</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
<section id="function-annotations">
|
||
<h3><a class="toc-backref" href="#function-annotations" role="doc-backlink">Function Annotations</a></h3>
|
||
<p>With the acceptance of <a class="pep reference internal" href="../pep-0484/" title="PEP 484 – Type Hints">PEP 484</a>, the style rules for function
|
||
annotations have changed.</p>
|
||
<ul>
|
||
<li>Function annotations should use <a class="pep reference internal" href="../pep-0484/" title="PEP 484 – Type Hints">PEP 484</a> syntax (there are some
|
||
formatting recommendations for annotations in the previous section).</li>
|
||
<li>The experimentation with annotation styles that was recommended
|
||
previously in this PEP is no longer encouraged.</li>
|
||
<li>However, outside the stdlib, experiments within the rules of <a class="pep reference internal" href="../pep-0484/" title="PEP 484 – Type Hints">PEP 484</a>
|
||
are now encouraged. For example, marking up a large third party
|
||
library or application with <a class="pep reference internal" href="../pep-0484/" title="PEP 484 – Type Hints">PEP 484</a> style type annotations,
|
||
reviewing how easy it was to add those annotations, and observing
|
||
whether their presence increases code understandability.</li>
|
||
<li>The Python standard library should be conservative in adopting such
|
||
annotations, but their use is allowed for new code and for big
|
||
refactorings.</li>
|
||
<li>For code that wants to make a different use of function annotations
|
||
it is recommended to put a comment of the form:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># type: ignore</span>
|
||
</pre></div>
|
||
</div>
|
||
<p>near the top of the file; this tells type checkers to ignore all
|
||
annotations. (More fine-grained ways of disabling complaints from
|
||
type checkers can be found in <a class="pep reference internal" href="../pep-0484/" title="PEP 484 – Type Hints">PEP 484</a>.)</p>
|
||
</li>
|
||
<li>Like linters, type checkers are optional, separate tools. Python
|
||
interpreters by default should not issue any messages due to type
|
||
checking and should not alter their behavior based on annotations.</li>
|
||
<li>Users who don’t want to use type checkers are free to ignore them.
|
||
However, it is expected that users of third party library packages
|
||
may want to run type checkers over those packages. For this purpose
|
||
<a class="pep reference internal" href="../pep-0484/" title="PEP 484 – Type Hints">PEP 484</a> recommends the use of stub files: .pyi files that are read
|
||
by the type checker in preference of the corresponding .py files.
|
||
Stub files can be distributed with a library, or separately (with
|
||
the library author’s permission) through the typeshed repo <a class="footnote-reference brackets" href="#id9" id="id5">[5]</a>.</li>
|
||
</ul>
|
||
</section>
|
||
<section id="variable-annotations">
|
||
<h3><a class="toc-backref" href="#variable-annotations" role="doc-backlink">Variable Annotations</a></h3>
|
||
<p><a class="pep reference internal" href="../pep-0526/" title="PEP 526 – Syntax for Variable Annotations">PEP 526</a> introduced variable annotations. The style recommendations for them are
|
||
similar to those on function annotations described above:</p>
|
||
<ul>
|
||
<li>Annotations for module level variables, class and instance variables,
|
||
and local variables should have a single space after the colon.</li>
|
||
<li>There should be no space before the colon.</li>
|
||
<li>If an assignment has a right hand side, then the equality sign should have
|
||
exactly one space on both sides:<div class="good highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Correct:</span>
|
||
|
||
<span class="n">code</span><span class="p">:</span> <span class="nb">int</span>
|
||
|
||
<span class="k">class</span> <span class="nc">Point</span><span class="p">:</span>
|
||
<span class="n">coords</span><span class="p">:</span> <span class="n">Tuple</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="nb">int</span><span class="p">]</span>
|
||
<span class="n">label</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">'<unknown>'</span>
|
||
</pre></div>
|
||
</div>
|
||
<div class="bad highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Wrong:</span>
|
||
|
||
<span class="n">code</span><span class="p">:</span><span class="nb">int</span> <span class="c1"># No space after colon</span>
|
||
<span class="n">code</span> <span class="p">:</span> <span class="nb">int</span> <span class="c1"># Space before colon</span>
|
||
|
||
<span class="k">class</span> <span class="nc">Test</span><span class="p">:</span>
|
||
<span class="n">result</span><span class="p">:</span> <span class="nb">int</span><span class="o">=</span><span class="mi">0</span> <span class="c1"># No spaces around equality sign</span>
|
||
</pre></div>
|
||
</div>
|
||
</li>
|
||
<li>Although the <a class="pep reference internal" href="../pep-0526/" title="PEP 526 – Syntax for Variable Annotations">PEP 526</a> is accepted for Python 3.6, the variable annotation
|
||
syntax is the preferred syntax for stub files on all versions of Python
|
||
(see <a class="pep reference internal" href="../pep-0484/" title="PEP 484 – Type Hints">PEP 484</a> for details).</li>
|
||
</ul>
|
||
<p class="rubric">Footnotes</p>
|
||
<aside class="footnote-list brackets">
|
||
<aside class="footnote brackets" id="fn-hi" role="doc-footnote">
|
||
<dt class="label" id="fn-hi">[<a href="#id2">1</a>]</dt>
|
||
<dd><em>Hanging indentation</em> is a type-setting style where all
|
||
the lines in a paragraph are indented except the first line. In
|
||
the context of Python, the term is used to describe a style where
|
||
the opening parenthesis of a parenthesized statement is the last
|
||
non-whitespace character of the line, with subsequent lines being
|
||
indented until the closing parenthesis.</aside>
|
||
</aside>
|
||
</section>
|
||
</section>
|
||
<section id="references">
|
||
<h2><a class="toc-backref" href="#references" role="doc-backlink">References</a></h2>
|
||
<aside class="footnote-list brackets">
|
||
<aside class="footnote brackets" id="id6" role="doc-footnote">
|
||
<dt class="label" id="id6">[<a href="#id1">2</a>]</dt>
|
||
<dd>Barry’s GNU Mailman style guide
|
||
<a class="reference external" href="http://barry.warsaw.us/software/STYLEGUIDE.txt">http://barry.warsaw.us/software/STYLEGUIDE.txt</a></aside>
|
||
<aside class="footnote brackets" id="id7" role="doc-footnote">
|
||
<dt class="label" id="id7">[<a href="#id3">3</a>]</dt>
|
||
<dd>Donald Knuth’s <em>The TeXBook</em>, pages 195 and 196.</aside>
|
||
<aside class="footnote brackets" id="id8" role="doc-footnote">
|
||
<dt class="label" id="id8">[<a href="#id4">4</a>]</dt>
|
||
<dd><a class="reference external" href="http://www.wikipedia.com/wiki/Camel_case">http://www.wikipedia.com/wiki/Camel_case</a></aside>
|
||
<aside class="footnote brackets" id="id9" role="doc-footnote">
|
||
<dt class="label" id="id9">[<a href="#id5">5</a>]</dt>
|
||
<dd>Typeshed repo
|
||
<a class="reference external" href="https://github.com/python/typeshed">https://github.com/python/typeshed</a></aside>
|
||
</aside>
|
||
</section>
|
||
<section id="copyright">
|
||
<h2><a class="toc-backref" href="#copyright" role="doc-backlink">Copyright</a></h2>
|
||
<p>This document has been placed in the public domain.</p>
|
||
</section>
|
||
</section>
|
||
<hr class="docutils" />
|
||
<p>Source: <a class="reference external" href="https://github.com/python/peps/blob/main/peps/pep-0008.rst">https://github.com/python/peps/blob/main/peps/pep-0008.rst</a></p>
|
||
<p>Last modified: <a class="reference external" href="https://github.com/python/peps/commits/main/peps/pep-0008.rst">2024-09-09 14:02:27 GMT</a></p>
|
||
|
||
</article>
|
||
<nav id="pep-sidebar">
|
||
<h2>Contents</h2>
|
||
<ul>
|
||
<li><a class="reference internal" href="#introduction">Introduction</a></li>
|
||
<li><a class="reference internal" href="#a-foolish-consistency-is-the-hobgoblin-of-little-minds">A Foolish Consistency is the Hobgoblin of Little Minds</a></li>
|
||
<li><a class="reference internal" href="#code-lay-out">Code Lay-out</a><ul>
|
||
<li><a class="reference internal" href="#indentation">Indentation</a></li>
|
||
<li><a class="reference internal" href="#tabs-or-spaces">Tabs or Spaces?</a></li>
|
||
<li><a class="reference internal" href="#maximum-line-length">Maximum Line Length</a></li>
|
||
<li><a class="reference internal" href="#should-a-line-break-before-or-after-a-binary-operator">Should a Line Break Before or After a Binary Operator?</a></li>
|
||
<li><a class="reference internal" href="#blank-lines">Blank Lines</a></li>
|
||
<li><a class="reference internal" href="#source-file-encoding">Source File Encoding</a></li>
|
||
<li><a class="reference internal" href="#imports">Imports</a></li>
|
||
<li><a class="reference internal" href="#module-level-dunder-names">Module Level Dunder Names</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#string-quotes">String Quotes</a></li>
|
||
<li><a class="reference internal" href="#whitespace-in-expressions-and-statements">Whitespace in Expressions and Statements</a><ul>
|
||
<li><a class="reference internal" href="#pet-peeves">Pet Peeves</a></li>
|
||
<li><a class="reference internal" href="#other-recommendations">Other Recommendations</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#when-to-use-trailing-commas">When to Use Trailing Commas</a></li>
|
||
<li><a class="reference internal" href="#comments">Comments</a><ul>
|
||
<li><a class="reference internal" href="#block-comments">Block Comments</a></li>
|
||
<li><a class="reference internal" href="#inline-comments">Inline Comments</a></li>
|
||
<li><a class="reference internal" href="#documentation-strings">Documentation Strings</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#naming-conventions">Naming Conventions</a><ul>
|
||
<li><a class="reference internal" href="#overriding-principle">Overriding Principle</a></li>
|
||
<li><a class="reference internal" href="#descriptive-naming-styles">Descriptive: Naming Styles</a></li>
|
||
<li><a class="reference internal" href="#prescriptive-naming-conventions">Prescriptive: Naming Conventions</a><ul>
|
||
<li><a class="reference internal" href="#names-to-avoid">Names to Avoid</a></li>
|
||
<li><a class="reference internal" href="#ascii-compatibility">ASCII Compatibility</a></li>
|
||
<li><a class="reference internal" href="#package-and-module-names">Package and Module Names</a></li>
|
||
<li><a class="reference internal" href="#class-names">Class Names</a></li>
|
||
<li><a class="reference internal" href="#type-variable-names">Type Variable Names</a></li>
|
||
<li><a class="reference internal" href="#exception-names">Exception Names</a></li>
|
||
<li><a class="reference internal" href="#global-variable-names">Global Variable Names</a></li>
|
||
<li><a class="reference internal" href="#function-and-variable-names">Function and Variable Names</a></li>
|
||
<li><a class="reference internal" href="#function-and-method-arguments">Function and Method Arguments</a></li>
|
||
<li><a class="reference internal" href="#method-names-and-instance-variables">Method Names and Instance Variables</a></li>
|
||
<li><a class="reference internal" href="#constants">Constants</a></li>
|
||
<li><a class="reference internal" href="#designing-for-inheritance">Designing for Inheritance</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#public-and-internal-interfaces">Public and Internal Interfaces</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#programming-recommendations">Programming Recommendations</a><ul>
|
||
<li><a class="reference internal" href="#function-annotations">Function Annotations</a></li>
|
||
<li><a class="reference internal" href="#variable-annotations">Variable Annotations</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a class="reference internal" href="#references">References</a></li>
|
||
<li><a class="reference internal" href="#copyright">Copyright</a></li>
|
||
</ul>
|
||
|
||
<br>
|
||
<a id="source" href="https://github.com/python/peps/blob/main/peps/pep-0008.rst">Page Source (GitHub)</a>
|
||
</nav>
|
||
</section>
|
||
<script src="../_static/colour_scheme.js"></script>
|
||
<script src="../_static/wrap_tables.js"></script>
|
||
<script src="../_static/sticky_banner.js"></script>
|
||
</body>
|
||
</html> |