Python Forgiveness vs. Permission and Duck Typing
Posted
by
darkfeline
on Programmers
See other posts from Programmers
or by darkfeline
Published on 2012-11-13T07:37:38Z
Indexed on
2012/11/13
11:20 UTC
Read the original article
Hit count: 537
In Python, I often hear that it is better to "beg forgiveness" (exception catching) instead of "ask permission" (type/condition checking). In regards to enforcing duck typing in Python, is this
try:
x = foo.bar
except AttributeError:
pass
else:
do(x)
better or worse than
if hasattr(foo, "bar"):
do(foo.bar)
else:
pass
in terms of performance, readability, "pythonic", or some other important factor?
© Programmers or respective owner