accurate EAFP (was Re: PEP308: Yet another syntax proposal)

Alex Martelli aleax at
Mon Feb 10 20:54:53 CET 2003

Andrew Dalke wrote:
> Or perhaps better as
>     try:
>         lines = source.readlines()
>     except AttributeError;
>         lines = source.split()

This popular idiom has a slight imperfection.  If source is an
object that has a buggy readlines method (and the bug makes 
it raise AttributeError), as well as a working split method,
this idiom hides the bug and unintendedly falls through to
the call to the split method.  The "right" way is something
just a tad more accurate/careful, such as:

try: method = source.readlines
except AttributeError: lines = source.split()
else: lines = method()

or variants thereof.  The key issue: when you catch an
AttributeError as an expected indication of "this object
has no such method", make sure you ONLY _access_ the
method object in the try clause, then call it later,
generally in an else clause -- so you won't accidentally
catch AttributeError exceptions propagated by _calling_
a method that is actually there.

This relates to the above-quoted, slightly imperfect variant 
of "easier to ask forgiveness than permission" (EAFP), a
bit like "Accurate LBYL" (Look Before You Leap) stands
to common or garden LBYL, whence my name for it...


More information about the Python-list mailing list