try/except KeyError vs "if name in ..."

Manuel Pégourié-Gonnard mpg at elzevir.fr
Sat Oct 6 02:27:25 EDT 2012


Hi,

I was looking at the example found here [1] which begins with:

[1] http://docs.python.org/py3k/library/imp.html#examples

def __import__(name, globals=None, locals=None, fromlist=None):
    # Fast path: see if the module has already been imported.
    try:
        return sys.modules[name]
    except KeyError:
        pass

I was wondering if the formulation

    if name in sys.modules:
        return sys.modules[name]

would be equivalent. IOW, is using try/except here only a matter of
style or a necessity?

I'm suspecting that maybe, in multithreaded environments, the second
option may be subject to a race condition, if another thread removes
name frome sys.modules between the if and the return, but as I'm not
very familiar (yet) with Python threads, I'm not sure it is a real
concern here.

And maybe there are other reasons I'm completely missing for prefering
EAFP over LBYL here?

Thanks in advance for your comments.

-- 
Manuel Pégourié-Gonnard - http://people.math.jussieu.fr/~mpg/





More information about the Python-list mailing list