EAFP gone wrong

Ben Finney ben+python at benfinney.id.au
Tue Feb 9 18:11:41 EST 2010


Arnaud Delobelle <arnodel at googlemail.com> writes:

> As I want to be able to typeset some builtin types as well, I have a
> generic function, latex(), as follows:
>
> def latex(val):
>     try:
>         return val.latex()
>     except AttributeError:
[…]

> It's EAFP and I have used this for a while with no problem.
[…]

> I found that there was a typo. Where it says:
>
>     latex(self.k)
>
> it should say:
>
>     latex(self.r)
>
> Thus it triggers an AttributeError, which is exactly the kind of
> exception that I am catching in the latex() function after trying
> val.latex(). (Of course I could have caught this by calling c.latex()
> directly but it's such a short method definition that I couldn't
> imagine missing the typo!).
>
> This means that EAFP made me hide a typo which would have been obviously
> detected had I LBYLed

The correct approach here is to reduce the operations being done in the
‘try’ suite to a minimum.

The fact that you're calling a function in the ‘try’ block obviously
opens you to the potential for an AttributeError from that function.
Since that's not what you intend to catch, you need to separate those
concerns.

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

-- 
 \           “Two hands working can do more than a thousand clasped in |
  `\                                               prayer.” —Anonymous |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list