[Tut] Python One Line Exception Handling - 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 Exception Handling (/thread-96460.html) |
[Tut] Python One Line Exception Handling - xSicKxBot - 07-29-2020 Python One Line Exception Handling <div><p class="has-pale-cyan-blue-background-color has-background"><strong>Summary</strong>: You can accomplish one line exception handling with the <code>exec()</code> workaround by passing the one-linerized <code>try</code>/<code>except</code> block as a string into the function like this: <code>exec('try:print(x)\nexcept:print("Exception!")')</code>. This general method works for all custom, even multi-line, try and except blocks. However, you should avoid this one-liner code due to the bad readability.</p> <p><em>Surprisingly, there has been a <a href="https://mail.python.org/pipermail/python-ideas/2013-March/019762.html" target="_blank" rel="noreferrer noopener" title="https://mail.python.org/pipermail/python-ideas/2013-March/019762.html">discussion </a>about one-line exception handling on the official Python mailing list in 2013. However, since then, there has been no new “One-Line Exception Handling” feature in Python. So, we need to stick with the methods shown in this tutorial. But they will be fun—promised! </em></p> <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 Exception Handling" width="1400" height="788" src="https://www.youtube.com/embed/RhP76e9HGOA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </div> </figure> <p>Let’s dive into the problem:</p> <p><strong>Problem</strong>: How to write the try/except block in a single line of Python code?</p> <p><strong>Example</strong>: Consider the following try/except 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="">try: print(x) except: print('Exception!')</pre> <p><strong>Solution</strong>: Before we dive into each of the three methods to solve this problem, let’s have a quick overview in our interactive code shell:</p> <p> <iframe height="700px" width="100%" src="https://repl.it/@finxter/StripedKindMemwatch?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> <p><em><strong>Exercise</strong>: Run the code. Why are there only three lines of output? Modify the code such that each of the four methods generate an output!</em></p> <h2>Method 1: Ternary Operator</h2> <p>The following method to replace a simple try/except statement is based on the <a href="https://blog.finxter.com/python-one-line-ternary/" title="Python One Line Ternary" target="_blank" rel="noreferrer noopener">ternary operator</a>.</p> <p><strong>Ternary Operator Background</strong>: The most basic ternary operator <code>x if c else y</code> consists of three operands <code>x</code>, <code>c</code>, and <code>y</code>. It is an expression with a return value. The ternary operator returns <code>x</code> if the Boolean expression <code>c</code> evaluates to <code>True</code>. Otherwise, if the expression <code>c</code> evaluates to <code>False</code>, the ternary operator returns the alternative <code>y</code>.</p> <p>You can use the <code>dir()</code> function to check if the variable name <code>'x'</code> already has been defined by using the condition <code>'x' in dir()</code>. If the condition evaluates to <code>True</code>, you run the try block. If it evaluates to <code>False</code>, you run the except 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=""># Method 1 print(x) if 'x' in dir() else print('Exception!')</pre> <p>The output of this code snippet as a standalone code is:</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="">Exception!</pre> <p>This is because the variable <code>x</code> is not defined and it doesn’t appear in the variable name directory:</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="">print(dir()) # ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']</pre> <p>For example, if you define variable x beforehand, the code would run through:</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="">x = 2 print(x) if 'x' in dir() else print('Exception!')</pre> <p>A disadvantage of this technique is that you need to know the kinds of exceptions that may occur. Also, it becomes harder to express multi-line try and except blocks. In this case, it’s often better to use the explicit try/except statements in the first place!</p> <h2>Method 2: exec()</h2> <p>The <code>exec()</code> function takes a string and runs the string as if it was a piece of source code. This way, you can compress any algorithm in a single line. You can also compress the try/except statement into a single line of code this way!</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=""># Method 2 exec('try:print(x)\nexcept:print("Exception!")')</pre> <p>If you’d define the variable x beforehand, the result would be different:</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="">exec('x=2\n' + 'try:print(x)\nexcept:print("Exception!")') # 2</pre> <p>Now, the variable 2 is defined and the try block of the statement runs without exception. </p> <h2>Method 3: Contextlib Suppress + With Statement</h2> <p>If you’re not really interested in the except part and you just need to catch exceptions, this method may be for you:</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=""># Method 3 from contextlib import suppress with suppress(NameError): print(x)</pre> <p>You use a <a href="https://blog.finxter.com/python-one-line-with-statement/" title="Python One Line With Statement" target="_blank" rel="noreferrer noopener">with block and write it into a single line</a>. The object you pass into the with block must define two functions <code>__enter__()</code> and <code>__exit__()</code>. You use the <code><a href="https://docs.python.org/3/library/contextlib.html#contextlib.suppress" target="_blank" rel="noreferrer noopener" title="https://docs.python.org/3/library/contextlib.html#contextlib.suppress">suppress()</a></code> method from the <code>contextlib</code> package to create such an object (a so-called <em>context manager</em>) that suppresses the occurrence of the NameError. The beauty of the with block is that it ensures that all errors on the <code>with</code> object are handled and the object is properly closed through the <code>__exit__()</code> method. </p> <p>The disadvantage or advantage—depending on your preferences—is that there’s no except block.</p> <p>Thanks for reading this blog tutorial! <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f642.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></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/28/python-one-line-exception-handling/ |