On Sat, 06 Oct 2012 08:27:25 +0200, Manuel Pégourié-Gonnard wrote: > 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?
Mostly style, but not entirely. 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. But see also: > 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 :) 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? -- Steven -- http://mail.python.org/mailman/listinfo/python-list