Schachjunge Schachjunge - 3 months ago 5
Python Question

Python how to use "try:" not stop when it raises except

I have this code and would like to shorten it. Is this anyway possible? Does not make that much sense to have that often the same code:



try:
years = values['year']
except KeyError:
pass

try:
tracks = values['track']
except KeyError:
pass

try:
statuses = values['status']
except KeyError:
pass




Answer

How about avoiding the exceptions entirely?

.get() allows you to provide a default value if they key doesn't exist already...

years = values.get('year', None)
tracks = values.get('track', None)
statuses = values.get('status', None)

As mentioned in comments by @DSM, this also guarantees that the variables will be bound with some value. Otherwise, attempting to use any of the variables might result in a NameError at run time.

Less efficient, but you can also explicitly check if a key exists...

if 'year' in values:
    # do something
Comments