Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: try statement in a single line

People also ask

How do you write an if-else in one line in Python?

Writing a one-line if-else statement in Python is possible by using the ternary operator, also known as the conditional expression. This works just fine. But you can get the job done by writing the if-else statement as a neat one-liner expression.

Can I use try without except in Python?

We cannot have the try block without except so, the only thing we can do is try to ignore the raised exception so that the code does not go the except block and specify the pass statement in the except block as shown earlier. The pass statement is equivalent to an empty line of code. We can also use the finally block.

How do you handle exceptions gracefully in Python?

Use Python try... except statement to handle exceptions gracefully. Use specific exception in the except block as much as possible. Use the except Exception statement to catch other exceptions.

Can you use try in an if statement Python?

Try-except statements are another selection structure in Python. Like if , elif and else statements, a try-except statements select a particular block of code to run based on a condition. Unlike if , elif and else clauses, try-except blocks are not based on logical conditions.


This is terribly hackish, but I've used it at the prompt when I wanted to write up a sequence of actions for debugging:

exec "try: some_problematic_thing()\nexcept: problem=sys.exc_info()"
print "The problem is %s" % problem[1]

For the most part, I'm not at all bothered by the no-single-line-try-except restriction, but when I'm just experimenting and I want readline to recall a whole chunk of code at once in the interactive interpreter so that I can adjust it somehow, this little trick comes in handy.

For the actual purpose you are trying to accomplish, you might try locals().get('c', b); ideally it would be better to use a real dictionary instead of the local context, or just assign c to None before running whatever may-or-may-not set it.


In python3 you can use contextlib.suppress:

from contextlib import suppress

d = {}
with suppress(KeyError): d['foo']

There is no way to compress a try/except block onto a single line in Python.

Also, it is a bad thing not to know whether a variable exists in Python, like you would in some other dynamic languages. The safer way (and the prevailing style) is to set all variables to something. If they might not get set, set them to None first (or 0 or '' or something if it is more applicable.)


If you do assign all the names you are interested in first, you do have options.

  • The best option is an if statement.

    c = None
    b = [1, 2]
    
    if c is None:
        a = b
    else:
        a = c
    
  • The one-liner option is a conditional expression.

    c = None
    b = [1, 2]
    a = c if c is not None else b
    
  • Some people abuse the short-circuiting behavior of or to do this. This is error prone, so I never use it.

    c = None
    b = [1, 2]
    a = c or b
    

    Consider the following case:

    c = []
    b = [1, 2]
    a = c or b
    

    In this case, a probably should be [], but it is [1, 2] because [] is false in a boolean context. Because there are lots of values that can be false, I don't use the or trick. (This is the same problem people run into when they say if foo: when they mean if foo is not None:.)


Version of poke53280 answer with limited expected exceptions.

def try_or(func, default=None, expected_exc=(Exception,)):
    try:
        return func()
    except expected_exc:
        return default

and it could be used as

In [2]: try_or(lambda: 1/2, default=float('nan'))
Out[2]: 0.5

In [3]: try_or(lambda: 1/0, default=float('nan'), expected_exc=(ArithmeticError,))
Out[3]: nan

In [4]: try_or(lambda: "1"/0, default=float('nan'), expected_exc=(ArithmeticError,))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
[your traceback here]
TypeError: unsupported operand type(s) for /: 'str' and 'int'

In [5]: try_or(lambda: "1"/0, default=float('nan'), expected_exc=(ArithmeticError, TypeError))
Out[5]: nan

Another way is to define a context manager:

class trialContextManager:
    def __enter__(self): pass
    def __exit__(self, *args): return True
trial = trialContextManager()

Then use the with statement to ignore errors in one single line:

>>> with trial: a = 5      # will be executed normally
>>> with trial: a = 1 / 0  # will be not executed and no exception is raised
>>> print a
5

No exception will be raised in case of a runtime error. It's like a try: without the except:.