{"id":116339,"date":"2020-07-27T09:33:40","date_gmt":"2020-07-27T09:33:40","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=11436"},"modified":"2020-07-27T09:33:40","modified_gmt":"2020-07-27T09:33:40","slug":"python-one-line-with-statement","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/27\/python-one-line-with-statement\/","title":{"rendered":"Python One Line With Statement"},"content":{"rendered":"<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<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>\n<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())\n<\/pre>\n<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>\n<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\nwith open('code.py') as code: print(code.read()) '''<\/pre>\n<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&#8217;t need to enclose the code with a <code>try...except<\/code> statement. <\/p>\n<h2>Single Expression &#8216;With&#8217; Statement in One Line<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" 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=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<p><strong>Problem<\/strong>: Can you write the <code>with<\/code> statement in a single line of code?<\/p>\n<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>\n<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>\n<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>\n<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>\n<p> <iframe loading=\"lazy\" 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>\n<h2>Multi Expression &#8216;With&#8217; Statement in One Line<\/h2>\n<p>If the body consists of multiple statements, you can use a semicolon between the different statements:<\/p>\n<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>\n<p>The previous code block becomes:<\/p>\n<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>\n<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>\n<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 decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/1f609.png\" alt=\"\ud83d\ude09\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<h2>Nested Indentation Blocks in a One-Line &#8216;With&#8217; Statement<\/h2>\n<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>&#8220;XYZ is impossible&#8221;<\/em> because in most cases, it isn&#8217;t. If you&#8217;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>&#8212;don&#8217;t. You can compress all algorithms into a single line!<\/p>\n<p>In most cases, you can avoid nested blocks by using<a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" title=\"List Comprehension in Python \u2014 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>\n<p>Consider the following example with a <code>for<\/code> loop inside a <code>with<\/code> block:<\/p>\n<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>\n<p><strong>Problem<\/strong>: One-Linerize a nested with block!<\/p>\n<p><strong>Wrong Solution<\/strong>: Write it into a single line:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img loading=\"lazy\" decoding=\"async\" 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=\"auto, (max-width: 641px) 100vw, 641px\" \/><\/figure>\n<\/div>\n<p><strong>Correct Solution<\/strong>: Replace the inner for loop with a list comprehension statement!<\/p>\n<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>\n<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&#8212;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&#8217;t any) so the output is not 10x only 1x the file contents. <\/p>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<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>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<h2>Python One-Liners Book<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<figure class=\"wp-block-image size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" 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=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<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 &#8220;one-liners&#8221;: concise statements of useful functionality packed into a single line of code. You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;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&#8217;ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You&#8217;ll also learn how to:<\/p>\n<p><strong>\u2022<\/strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;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>\u2022<\/strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting<\/p>\n<p>By the end of the book, you&#8217;ll know how to write Python at its most refined, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>The with statement replaces former try&#8230;finally 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 &#8216;code.py&#8217;): with open(&#8216;code.py&#8217;) as code: print(code.read()) The output of this code would be the code itself [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-116339","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/116339","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=116339"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/116339\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=116339"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=116339"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=116339"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}