![]() |
|
[Tut] Python One Line Exception Handling - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://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 Summary: You can accomplish one line exception handling with the Code: exec()Code: tryCode: exceptCode: exec('try:print(x)\nexcept:print("Exception!")')Surprisingly, there has been a discussionabout 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! Let’s dive into the problem: Problem: How to write the try/except block in a single line of Python code? Example: Consider the following try/except block. Code: try: print(x)
except: print('Exception!')Solution: Before we dive into each of the three methods to solve this problem, let’s have a quick overview in our interactive code shell: https://repl.it/@finxter/StripedKindMemwatch?lite=true Exercise: Run the code. Why are there only three lines of output? Modify the code such that each of the four methods generate an output! Method 1: Ternary Operator The following method to replace a simple try/except statement is based on the ternary operator. Ternary Operator Background: The most basic ternary operator Code: x if c else yCode: xCode: cCode: yCode: xCode: cCode: TrueCode: cCode: FalseCode: yYou can use the Code: dir()Code: 'x'Code: 'x' in dir()Code: TrueCode: FalseCode: # Method 1
print(x) if 'x' in dir() else print('Exception!')The output of this code snippet as a standalone code is: Code: Exception!This is because the variable Code: xCode: print(dir())
# ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']For example, if you define variable x beforehand, the code would run through: Code: x = 2
print(x) if 'x' in dir() else print('Exception!')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! Method 2: exec() The Code: exec()Code: # Method 2
exec('try:print(x)\nexcept:print("Exception!")')If you’d define the variable x beforehand, the result would be different: Code: exec('x=2\n' + 'try:print(x)\nexcept:print("Exception!")')
# 2Now, the variable 2 is defined and the try block of the statement runs without exception. Method 3: Contextlib Suppress + With Statement If you’re not really interested in the except part and you just need to catch exceptions, this method may be for you: Code: # Method 3
from contextlib import suppress
with suppress(NameError): print(x)You use a with block and write it into a single line. The object you pass into the with block must define two functions Code: __enter__()Code: __exit__()Code: suppress()Code: contextlibCode: withCode: __exit__()The disadvantage or advantage—depending on your preferences—is that there’s no except block. Thanks for reading this blog tutorial! ![]() Python One-Liners Book Python programmers will improve their computer science skills with these useful one-liners. ![]() Python One-Linerswill 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. 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: • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning • 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 • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting 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. Get your Python One-Liners Now!! |