Live data from Hacker News

Python Idioms [pdf]

safehammad.com

1–10 of 128 posts

Re: Python Idioms [pdf]

#3
I 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 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]

#6
post #3

I 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…

While not disagreeing with your case, there are some cases where I try to follow this rule because in most of those cases, I would expect that there is no exception and if there is, then catch it.

  try:
      open(FILE)
  except IOError:
      it failed

Re: Python Idioms [pdf]

#9
post #3

I 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…

Also note the second argument to the get method specifies the default value to return in case of a KeyError:

    something = d.get('x', default)

Re: Python Idioms [pdf]

#10
post #3

I 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…

That example would surely be better as:

    something = myfunc(d['x']) if 'x' in d else None
Post reply on HN