{"id":115976,"date":"2020-07-28T07:33:26","date_gmt":"2020-07-28T07:33:26","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=11464"},"modified":"2020-07-28T07:33:26","modified_gmt":"2020-07-28T07:33:26","slug":"python-one-line-exception-handling","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/07\/28\/python-one-line-exception-handling\/","title":{"rendered":"Python One Line Exception Handling"},"content":{"rendered":"<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>\n<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 &#8220;One-Line Exception Handling&#8221; feature in Python. So, we need to stick with the methods shown in this tutorial. But they will be fun&#8212;promised! <\/em><\/p>\n<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 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>\n<\/div>\n<\/figure>\n<p>Let&#8217;s dive into the problem:<\/p>\n<p><strong>Problem<\/strong>: How to write the try\/except block in a single line of Python code?<\/p>\n<p><strong>Example<\/strong>: Consider the following try\/except 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=\"\">try: print(x)\nexcept: print('Exception!')<\/pre>\n<p><strong>Solution<\/strong>: Before we dive into each of the three methods to solve this problem, let&#8217;s have a quick overview in our interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" 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>\n<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>\n<h2>Method 1: Ternary Operator<\/h2>\n<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>\n<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>\n<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>\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=\"\"># Method 1\nprint(x) if 'x' in dir() else print('Exception!')<\/pre>\n<p>The output of this code snippet as a standalone code is:<\/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=\"\">Exception!<\/pre>\n<p>This is because the variable <code>x<\/code> is not defined and it doesn&#8217;t appear in the variable name directory:<\/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=\"\">print(dir())\n# ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']<\/pre>\n<p>For example, if you define variable x beforehand, the code would run through:<\/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=\"\">x = 2\nprint(x) if 'x' in dir() else print('Exception!')<\/pre>\n<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&#8217;s often better to use the explicit try\/except statements in the first place!<\/p>\n<h2>Method 2: exec()<\/h2>\n<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>\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=\"\"># Method 2\nexec('try:print(x)\\nexcept:print(\"Exception!\")')<\/pre>\n<p>If you&#8217;d define the variable x beforehand, the result would be different:<\/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=\"\">exec('x=2\\n' + 'try:print(x)\\nexcept:print(\"Exception!\")')\n# 2<\/pre>\n<p>Now, the variable 2 is defined and the try block of the statement runs without exception. <\/p>\n<h2>Method 3: Contextlib Suppress + With Statement<\/h2>\n<p>If you&#8217;re not really interested in the except part and you just need to catch exceptions, this method may be for you:<\/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=\"\"># Method 3\nfrom contextlib import suppress\nwith suppress(NameError): print(x)<\/pre>\n<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>\n<p>The disadvantage or advantage&#8212;depending on your preferences&#8212;is that there&#8217;s no except block.<\/p>\n<p>Thanks for reading this blog tutorial! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/1f642.png\" alt=\"\ud83d\ude42\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/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>Summary: You can accomplish one line exception handling with the exec() workaround by passing the one-linerized try\/except block as a string into the function like this: exec(&#8216;try:print(x)\\nexcept:print(&#8220;Exception!&#8221;)&#8217;). 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. Surprisingly, there has [&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-115976","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\/115976","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=115976"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/115976\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=115976"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=115976"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=115976"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}