Python Idioms [pdf]
safehammad.com
Python Idioms [pdf]
1–10 of 128 posts
Re: Python Idioms [pdf]
#2Re: Python Idioms [pdf]
#3E.g. something like:
try:
something = myfunc(d['x'])
except ValueError:
something = None
The programmer's intent is probably to only catch errors in the key lookup d['x'], but if there is some bug in the implementation of myfunc() or any of the functions called by myfunc() which causes a ValueError to unintentionally be raised, it will be caught by the except.For dictionary lookups specifically, get() is usually preferable:
something = d.get('x')
if something is not None:
something = myfunc(something)
Or if dictionary may potentially contain None values: if 'x' in d:
something = myfunc(d['x'])Re: Python Idioms [pdf]
#4In 2.7+, I'd recommend a dictionary comprehension instead.
Re: Python Idioms [pdf]
#5Re: Python Idioms [pdf]
#6I disagree with promoting try / catch. Exceptions like ValueError can really happen almost anywhere, so it is usually better to sanitize your inputs. E.g. something like: try: something = myfunc(d['x']) except ValueError: something = None The programmer's intent is probably to only catch errors in the key lookup d['x'], but if there is some bug in the implementation of myfunc() or any of the functions called by myfun…
try:
open(FILE)
except IOError:
it failedRe: Python Idioms [pdf]
#7 with open("x.txt") as f:
data = f.read()
# do something with dataRe: Python Idioms [pdf]
#8 ''.join('Thanks!')Re: Python Idioms [pdf]
#9I disagree with promoting try / catch. Exceptions like ValueError can really happen almost anywhere, so it is usually better to sanitize your inputs. E.g. something like: try: something = myfunc(d['x']) except ValueError: something = None The programmer's intent is probably to only catch errors in the key lookup d['x'], but if there is some bug in the implementation of myfunc() or any of the functions called by myfun…
something = d.get('x', default)Re: Python Idioms [pdf]
#10I disagree with promoting try / catch. Exceptions like ValueError can really happen almost anywhere, so it is usually better to sanitize your inputs. E.g. something like: try: something = myfunc(d['x']) except ValueError: something = None The programmer's intent is probably to only catch errors in the key lookup d['x'], but if there is some bug in the implementation of myfunc() or any of the functions called by myfun…
something = myfunc(d['x']) if 'x' in d else None