08-04-2020, 06:51 AM
PEP 8: Hanging Indentation and Closing Brackets in Python
<div><figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="PEP 8: Hanging Indentation and Closing Brackets in Python" width="1400" height="788" src="https://www.youtube.com/embed/DfqlKhESeOo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>PEP 8 purists are ready to attack you and your code if they catch you not complying with the <a href="https://www.python.org/dev/peps/pep-0008/">PEP 8 standard</a>. For instance, Python coders put their braces, brackets, or parentheses into a separate line to make it easier to grasp <a href="https://blog.finxter.com/python-list-of-lists/" title="Python List of Lists – A Helpful Illustrated Guide to Nested Lists in Python" target="_blank" rel="noreferrer noopener">nested lists</a> or <a href="https://blog.finxter.com/python-dictionary/" title="Python Dictionary – The Ultimate Guide" target="_blank" rel="noreferrer noopener">dictionaries</a>. </p>
<p><strong><em>This article shows how to line up the closing braces, brackets, and parentheses correctly in Python. </em></strong>This is called “hanging indentation” and it’s at the heart of <a href="https://www.python.org/dev/peps/pep-0008/#indentation" target="_blank" rel="noreferrer noopener" title="https://www.python.org/dev/peps/pep-0008/#indentation">PEP 8 standardized</a>, clean code that’s easy to read and understand!</p>
<p>A quick example shows how you can create a multi-line construct that complies with the PEP 8 standard:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26, }</pre>
<p><strong>So, how to correctly intend list or dictionary data enclosed in braces, brackets, and parentheses?</strong></p>
<p class="has-pale-cyan-blue-background-color has-background">According to the PEP 8 standard, there are two ways to line up the closing braces, brackets, or parentheses. First, line it up with the first non-whitespace character of the previous line. Second, line it up with the first character that starts the multi-line construct. </p>
<p>This sounds a bit confusing so let’s hop into practical examples.</p>
<h2>Where to Put the Closing Brace, Bracket, or Parenthesis?</h2>
<p>For multi-line constructs, there are two basic options of how to correctly intend the data.</p>
<p><strong>1. Align the closing brace with the first non-whitespace character of the previous line</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26, }</pre>
<p><strong>2. Align the closing brace with the first character that starts the multi-line construct</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26,
}
</pre>
<p>Both ways of indentation are equally valid <a href="https://www.python.org/dev/peps/pep-0008/#indentation">according to the PEP 8 standard</a>. But note that in any case, the opening and closing braces (brackets, parentheses) should be placed in their own line. So the following would be a violation of the PEP 8 standard:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># NOT PEP 8 COMPLIANT
age = {'Alice': 24, 'Bob': 28, 'Ann': 26, }</pre>
<p>The reason is that both opening and closing braces (brackets, parentheses) should be placed in their own line.</p>
<p>However, the <a href="https://www.python.org/dev/peps/pep-0008/#id17">PEP 8 standard </a>allows NOT to place both opening and closing braces (brackets, parentheses) into their own line—IF the arguments or items align. Here are three PEP 8 compliant examples:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
def f(argument_1, argument_2, argument_3, argument_4): None # PEP 8 Compliant
def f(argument_1, argument_2, argument_3, argument_4): None # PEP 8 Compliant
def f(argument_1, argument_2, argument_3, argument_4): None</pre>
<p>Although the opening and closing parentheses are not placed into their own lines, it’s still PEP 8 compliant because the arguments align in the first two examples.</p>
<p>The following interactive code is not ready, yet. It requires your debugging superpower:</p>
<p> <iframe src="https://trinket.io/embed/python/d548a09718" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<p><em><strong>Exercise</strong>: Debug the code so that it runs. Which indentation method is your preferred one?</em></p>
</p>
<h2> Why End Python List with Trailing Comma? </h2>
<p>We’ve seen many examples of multi-line constructs where there’s a trailing comma after the last list element:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26, }</pre>
<p>The trailing comma after the last line in the dictionary (<code>'Ann' : 26,</code>) is <strong>optional </strong>according to the <a href="https://www.python.org/dev/peps/pep-0008/#id29">PEP 8 standard</a>. </p>
<p><strong>Be aware:</strong> you’ll find many opinions on the web where “experts” tell you that the trailing comma is required (like <a href="https://community.lsst.org/t/pep8-style-hanging-indentation-and-closing-brackets/618">here</a>). But this is not explicitly stated in the standard. In fact, the standard recommends that you use the comma if your <strong>“items [are] expected to be extended over time”</strong> (<a href="https://www.python.org/dev/peps/pep-0008/#when-to-use-trailing-commas">source</a>). In this case, it’s easier to copy&paste new items into the list (or dictionary) without having to manually add a trailing comma to the old last item and removing the trailing comma after the new last item.</p>
<p>In other words, the following multi-line construct is also valid and implicitly follows the PEP 8 standard:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26 }</pre>
<p>Note that the trailing comma is missing. But if you don’t plan to extend your list over time, it’s fine to use this—even if some <a href="https://www.pylint.org/">Python code style checkers</a> (“Linters”) complain.</p>
<h2>Nested Multi-Line Constructs</h2>
<p>Now, you simply need to decide about which of the above methods you prepare to write opening and closing braces, brackets, or parentheses. Here’s how you can nest those and comply with the PEP 8 standard:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
data = [ 'string', 42, { 1: '1', 2: '2', 42: '21', }, (1, 2, 3), ( [1, 2, 3], [4, 5, 6], )
]</pre>
<p>You see that we place each brace, bracket, and parenthesis in one line. The next line starts with four whitespace indentations. Then comes the item, followed by a comma. The item itself can be a multi-line construct as well. But if you understand how to write one multi-line construct, you’ll also understand how to nest them.</p>
<h2>Similar Questions</h2>
<p><strong>Should curly braces appear on their own line?</strong></p>
<p>Yes, they should appear on their own line. An exception is if you write the whole sequence of items in one line. In this case, the closing brace, bracket, or parenthesis should appear at the end of the same line, too.</p>
<p><strong>Where to Put the Closing Brace?</strong></p>
<p>As discussed previously, you line it up with the first non-whitespace character of the previous line, or with the first character that starts the multi-line construct. </p>
<h2>Flake-8 Rule: Continuation line unaligned for hanging indent (E131)</h2>
<p>This is a <a href="https://www.flake8rules.com/rules/E131.html" target="_blank" rel="noreferrer noopener" title="https://www.flake8rules.com/rules/E131.html">common error of the code analyzer Flake-8</a>. A continuation line is unaligned for hanging indent.</p>
<p id="anti-pattern"><strong>Anti-pattern</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># NOT PEP 8 Compliant
my_dict = { "key": "value", "long": "the quick brown fox jumps over the " "lazy dog",
}
</pre>
<p id="best-practice"><strong>Best practice</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
my_dict = { "key": "value", "long": "the quick brown fox jumps over the " "lazy dog",
}
</pre>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>
https://www.sickgaming.net/blog/2020/07/...in-python/
<div><figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="PEP 8: Hanging Indentation and Closing Brackets in Python" width="1400" height="788" src="https://www.youtube.com/embed/DfqlKhESeOo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>PEP 8 purists are ready to attack you and your code if they catch you not complying with the <a href="https://www.python.org/dev/peps/pep-0008/">PEP 8 standard</a>. For instance, Python coders put their braces, brackets, or parentheses into a separate line to make it easier to grasp <a href="https://blog.finxter.com/python-list-of-lists/" title="Python List of Lists – A Helpful Illustrated Guide to Nested Lists in Python" target="_blank" rel="noreferrer noopener">nested lists</a> or <a href="https://blog.finxter.com/python-dictionary/" title="Python Dictionary – The Ultimate Guide" target="_blank" rel="noreferrer noopener">dictionaries</a>. </p>
<p><strong><em>This article shows how to line up the closing braces, brackets, and parentheses correctly in Python. </em></strong>This is called “hanging indentation” and it’s at the heart of <a href="https://www.python.org/dev/peps/pep-0008/#indentation" target="_blank" rel="noreferrer noopener" title="https://www.python.org/dev/peps/pep-0008/#indentation">PEP 8 standardized</a>, clean code that’s easy to read and understand!</p>
<p>A quick example shows how you can create a multi-line construct that complies with the PEP 8 standard:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26, }</pre>
<p><strong>So, how to correctly intend list or dictionary data enclosed in braces, brackets, and parentheses?</strong></p>
<p class="has-pale-cyan-blue-background-color has-background">According to the PEP 8 standard, there are two ways to line up the closing braces, brackets, or parentheses. First, line it up with the first non-whitespace character of the previous line. Second, line it up with the first character that starts the multi-line construct. </p>
<p>This sounds a bit confusing so let’s hop into practical examples.</p>
<h2>Where to Put the Closing Brace, Bracket, or Parenthesis?</h2>
<p>For multi-line constructs, there are two basic options of how to correctly intend the data.</p>
<p><strong>1. Align the closing brace with the first non-whitespace character of the previous line</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26, }</pre>
<p><strong>2. Align the closing brace with the first character that starts the multi-line construct</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26,
}
</pre>
<p>Both ways of indentation are equally valid <a href="https://www.python.org/dev/peps/pep-0008/#indentation">according to the PEP 8 standard</a>. But note that in any case, the opening and closing braces (brackets, parentheses) should be placed in their own line. So the following would be a violation of the PEP 8 standard:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># NOT PEP 8 COMPLIANT
age = {'Alice': 24, 'Bob': 28, 'Ann': 26, }</pre>
<p>The reason is that both opening and closing braces (brackets, parentheses) should be placed in their own line.</p>
<p>However, the <a href="https://www.python.org/dev/peps/pep-0008/#id17">PEP 8 standard </a>allows NOT to place both opening and closing braces (brackets, parentheses) into their own line—IF the arguments or items align. Here are three PEP 8 compliant examples:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
def f(argument_1, argument_2, argument_3, argument_4): None # PEP 8 Compliant
def f(argument_1, argument_2, argument_3, argument_4): None # PEP 8 Compliant
def f(argument_1, argument_2, argument_3, argument_4): None</pre>
<p>Although the opening and closing parentheses are not placed into their own lines, it’s still PEP 8 compliant because the arguments align in the first two examples.</p>
<p>The following interactive code is not ready, yet. It requires your debugging superpower:</p>
<p> <iframe src="https://trinket.io/embed/python/d548a09718" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<p><em><strong>Exercise</strong>: Debug the code so that it runs. Which indentation method is your preferred one?</em></p>
</p>
<h2> Why End Python List with Trailing Comma? </h2>
<p>We’ve seen many examples of multi-line constructs where there’s a trailing comma after the last list element:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26, }</pre>
<p>The trailing comma after the last line in the dictionary (<code>'Ann' : 26,</code>) is <strong>optional </strong>according to the <a href="https://www.python.org/dev/peps/pep-0008/#id29">PEP 8 standard</a>. </p>
<p><strong>Be aware:</strong> you’ll find many opinions on the web where “experts” tell you that the trailing comma is required (like <a href="https://community.lsst.org/t/pep8-style-hanging-indentation-and-closing-brackets/618">here</a>). But this is not explicitly stated in the standard. In fact, the standard recommends that you use the comma if your <strong>“items [are] expected to be extended over time”</strong> (<a href="https://www.python.org/dev/peps/pep-0008/#when-to-use-trailing-commas">source</a>). In this case, it’s easier to copy&paste new items into the list (or dictionary) without having to manually add a trailing comma to the old last item and removing the trailing comma after the new last item.</p>
<p>In other words, the following multi-line construct is also valid and implicitly follows the PEP 8 standard:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
age = { 'Alice': 24, 'Bob': 28, 'Ann': 26 }</pre>
<p>Note that the trailing comma is missing. But if you don’t plan to extend your list over time, it’s fine to use this—even if some <a href="https://www.pylint.org/">Python code style checkers</a> (“Linters”) complain.</p>
<h2>Nested Multi-Line Constructs</h2>
<p>Now, you simply need to decide about which of the above methods you prepare to write opening and closing braces, brackets, or parentheses. Here’s how you can nest those and comply with the PEP 8 standard:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
data = [ 'string', 42, { 1: '1', 2: '2', 42: '21', }, (1, 2, 3), ( [1, 2, 3], [4, 5, 6], )
]</pre>
<p>You see that we place each brace, bracket, and parenthesis in one line. The next line starts with four whitespace indentations. Then comes the item, followed by a comma. The item itself can be a multi-line construct as well. But if you understand how to write one multi-line construct, you’ll also understand how to nest them.</p>
<h2>Similar Questions</h2>
<p><strong>Should curly braces appear on their own line?</strong></p>
<p>Yes, they should appear on their own line. An exception is if you write the whole sequence of items in one line. In this case, the closing brace, bracket, or parenthesis should appear at the end of the same line, too.</p>
<p><strong>Where to Put the Closing Brace?</strong></p>
<p>As discussed previously, you line it up with the first non-whitespace character of the previous line, or with the first character that starts the multi-line construct. </p>
<h2>Flake-8 Rule: Continuation line unaligned for hanging indent (E131)</h2>
<p>This is a <a href="https://www.flake8rules.com/rules/E131.html" target="_blank" rel="noreferrer noopener" title="https://www.flake8rules.com/rules/E131.html">common error of the code analyzer Flake-8</a>. A continuation line is unaligned for hanging indent.</p>
<p id="anti-pattern"><strong>Anti-pattern</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># NOT PEP 8 Compliant
my_dict = { "key": "value", "long": "the quick brown fox jumps over the " "lazy dog",
}
</pre>
<p id="best-practice"><strong>Best practice</strong>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># PEP 8 Compliant
my_dict = { "key": "value", "long": "the quick brown fox jumps over the " "lazy dog",
}
</pre>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>
https://www.sickgaming.net/blog/2020/07/...in-python/