Summary: You can accomplish one line exception handling with the
exec() workaround by passing the one-linerized
except block as a string into the function like this:
exec('try:print(x)\nexcept:print("Exception!")'). 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 been a discussion 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!
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.
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:
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
x if c else y consists of three operands
y. It is an expression with a return value. The ternary operator returns
x if the Boolean expression
c evaluates to
True. Otherwise, if the expression
c evaluates to
False, the ternary operator returns the alternative
You can use the
dir() function to check if the variable name
'x' already has been defined by using the condition
'x' in dir(). If the condition evaluates to
True, you run the try block. If it evaluates to
False, you run the except block.
# Method 1 print(x) if 'x' in dir() else print('Exception!')
The output of this code snippet as a standalone code is:
This is because the variable
x is not defined and it doesn’t appear in the variable name directory:
print(dir()) # ['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
For example, if you define variable x beforehand, the code would run through:
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()
exec() 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!
# Method 2 exec('try:print(x)\nexcept:print("Exception!")')
If you’d define the variable x beforehand, the result would be different:
exec('x=2\n' + 'try:print(x)\nexcept:print("Exception!")') # 2
Now, 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:
# 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
__exit__(). You use the
suppress() method from the
contextlib package to create such an object (a so-called context manager) that suppresses the occurrence of the NameError. The beauty of the with block is that it ensures that all errors on the
with object are handled and the object is properly closed through the
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: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners 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.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) 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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.