EAFP gone wrong
Malte Helmert
helmert at informatik.uni-freiburg.de
Tue Feb 9 18:27:10 EST 2010
Ben Finney wrote:
> def latex(val):
> def make_result_in_the_absence_of_a_latex_method():
> result = transmogrify(val)
> return result
>
> try:
> typeset_func = val.latex
> except AttributeError:
> typeset_func = make_result_in_the_absence_of_a_latex_method
>
> result = typeset_func()
> return result
In this particular case, where in the case of an AttributeError you want
to use a fallback callable with the same signature as the bound method
you get in case of success, I'd say getattr with a default is the nicest
approach:
def latex(val):
def make_result_in_the_absence_of_a_latex_method():
result = transmogrify(val)
return result
return getattr(val, "latex",
make_result_in_the_absence_of_a_latex_method)()
Doesn't work as nicely if you don't have
make_result_in_the_absence_of_a_latex_method's functionality bundled
into a suitable function already, though.
Malte
More information about the Python-list
mailing list