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

Manuel Pégourié-Gonnard mpg at elzevir.fr
Sat Oct 6 06:08:26 EDT 2012


Steven D'Aprano scripsit :

> If you expect that most of the time the module will be found, the 
> try...except version will be faster. If you expect that most of the time 
> the module will not be found, the "if name in" version will be faster.
>
Ok.

In the particular case of __import__, I guess speed is not crucial since
I doubt import often happen within a program's inner loop. But I'll
remember that point for other cases anyway.

>> 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.
>
> In practice, no, it would be very unusual for another thread to remove 
> the name from sys.modules. So don't do that :)
>
That wasn't my intention. But sometimes other people may be "creative" :)

> But in principle, yes, it is a race condition and yes it is a (small) 
> concern. Since it is so easy to avoid even this tiny risk, why not use 
> the try...except version and avoid it completely?
>
Ok.

Thanks for your explanations.

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





More information about the Python-list mailing list