[Tut] Python One Line With Statement - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Python One Line With Statement (/thread-96585.html) |
[Tut] Python One Line With Statement - xSicKxBot - 08-06-2020 Python One Line With Statement <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="Python One Line With Statement" width="1400" height="788" src="https://www.youtube.com/embed/akQ9cjKBaE8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </div> </figure> <p>The <code><a href="https://docs.python.org/2.5/whatsnew/pep-343.html" target="_blank" rel="noreferrer noopener" title="https://docs.python.org/2.5/whatsnew/pep-343.html">with</a></code> statement replaces former <code>try...finally</code> blocks in Python. It ensures that clean-up code is executed. For example, it closes open files before leaving the block. Consider this code example (assuming this code is stored in a file named <code>'code.py'</code>):</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="">with open('code.py') as code: print(code.read()) </pre> <p>The output of this code would be the code itself (for nerds: <a href="https://blog.finxter.com/python-quine/" title="Python One Line Quine" target="_blank" rel="noreferrer noopener">a piece of code that generates itself is called a <strong><em>Quine</em></strong></a>): </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="">''' OUTPUT with open('code.py') as code: print(code.read()) '''</pre> <p>No matter what goes wrong inside the <code>with</code> block, Python will close the open file before moving on in the code. This way, you don’t need to enclose the code with a <code>try...except</code> statement. </p> <h2>Single Expression ‘With’ Statement in One Line</h2> <div class="wp-block-image"> <figure class="aligncenter size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/07/pythononelinewith-1024x576.jpg" alt="Python One Line With Statement" class="wp-image-11448" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/07/pythononelinewith-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/07/pythononelinewith-300x169.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/07/pythononelinewith-768x432.jpg 768w, https://blog.finxter.com/wp-content/uploads/2020/07/pythononelinewith-150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" /></figure> </div> <p><strong>Problem</strong>: Can you write the <code>with</code> statement in a single line of code?</p> <p><strong>Solution</strong>: Yes, you can write the <code>with</code> statement in a single line of code if the loop body consists only of one statement:</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="">with open('code.py') as code: print(code.read())</pre> <p>In general, you can write any indentation block (like <code><a href="https://blog.finxter.com/if-then-else-in-one-line-python/" title="If-Then-Else in One Line Python [Video + Interactive Code Shell]">if</a></code> statements, <code>with</code> environments, or <code><a href="https://blog.finxter.com/python-one-line-while-loop-a-simple-tutorial/" title="Python One Line While Loop [A Simple Tutorial]">while</a></code> loops) in a single line of code if the body consists of only one statement. </p> <p><em><strong>Exercise</strong>: The following interactive code throws an error if you run it. Fix the bug and run the correct code!</em></p> <p> <iframe height="400px" width="100%" src="https://repl.it/@finxter/ClientsideGrownBrace?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p> <h2>Multi Expression ‘With’ Statement in One Line</h2> <p>If the body consists of multiple statements, you can use a semicolon between the different statements:</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="">with open('code.py') as code: print('The code:') print(code.read())</pre> <p>The previous code block becomes:</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="">with open('code.py') as code: print('The code:'); print(code.read())</pre> <p>Note that in this particular instance, the semantics actually change because the code reads its own source file! But in all other cases, the semantics remain the same. </p> <p>As soon as you have nested blocks like a <code>for</code> <a href="https://blog.finxter.com/python-loops/" title="Python Loops" target="_blank" rel="noreferrer noopener">loop </a>inside a <code>with</code> block, you cannot use this approach anymore because the code would become ambiguous. Believe it or not but the indentation serves a real purpose in Python! <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f609.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <h2>Nested Indentation Blocks in a One-Line ‘With’ Statement</h2> <p>If you know the <a href="https://blog.finxter.com/subscribe/" title="Subscribe" target="_blank" rel="noreferrer noopener">Finxter tutorials</a>, you also know that I seldomly conclude with such a statement <em>“XYZ is impossible”</em> because in most cases, it isn’t. If you’re in doubt whether you can compress an algorithm into a <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener" title="https://pythononeliners.com/">single line of code</a>—don’t. You can compress all algorithms into a single line!</p> <p>In most cases, you can avoid nested blocks by using<a href="https://blog.finxter.com/list-comprehension/" title="List Comprehension in Python — A Helpful Illustrated Guide" target="_blank" rel="noreferrer noopener"> list comprehension</a> (rather than a <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" title="Python One Line For Loop [A Simple Tutorial]" target="_blank" rel="noreferrer noopener"><code>for</code> loop</a>) or the<a href="https://blog.finxter.com/python-one-line-ternary/" title="Python One Line Ternary" target="_blank" rel="noreferrer noopener"> ternary operator</a> (rather than an <code>if</code> block). </p> <p>Consider the following example with a <code>for</code> loop inside a <code>with</code> block:</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="">with open('code.py') as code: for i in range(10): print(code.read())</pre> <p><strong>Problem</strong>: One-Linerize a nested with block!</p> <p><strong>Wrong Solution</strong>: Write it into a single line:</p> <div class="wp-block-image"> <figure class="aligncenter size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/07/image-32.png" alt="Syntax Error With Statement Single Line" class="wp-image-11439" width="641" height="236" srcset="https://blog.finxter.com/wp-content/uploads/2020/07/image-32.png 854w, https://blog.finxter.com/wp-content/uploads/2020/07/image-32-300x110.png 300w, https://blog.finxter.com/wp-content/uploads/2020/07/image-32-768x282.png 768w, https://blog.finxter.com/wp-content/uploads/2020/07/image-32-150x55.png 150w" sizes="(max-width: 641px) 100vw, 641px" /></figure> </div> <p><strong>Correct Solution</strong>: Replace the inner for loop with a list comprehension statement!</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="">with open('code.py') as code: [print(code.read()) for i in range(10)]</pre> <p>While this code runs and solves the problem, please note that the chosen example does not make a lot of sense. The file is read only once—even if you place it into a for loop. The reason is that the file reader is done reading the file after the first iteration. In subsequent iterations it only reads the remaining characters (there aren’t any) so the output is not 10x only 1x the file contents. </p> <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> <h2>Python One-Liners Book</h2> <p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p> <figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-300x277.jpg 300w, https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-768x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure> <p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p> <p>The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:</p> <p><strong>•</strong> Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br /><strong>•</strong> Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br /><strong>•</strong> Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br /><strong>•</strong> Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators<br /><strong>•</strong> Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting</p> <p>By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.</p> <p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners Now!!</em></a></strong></p> </div> https://www.sickgaming.net/blog/2020/07/27/python-one-line-with-statement/ |