__file__ access extremely slow

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Jun 4 22:40:01 EDT 2009


On Fri, 05 Jun 2009 02:21:07 +0000, Steven D'Aprano wrote:

> You corrected this to:
> 
> for module in sys.modules.itervalues():
>        try:
>                path = module.__file__
>        except (AttributeError, ImportError):
>                return
> 
> (1) You're not importing anything inside the try block. Why do you think
> ImportError could be raised?
> 
> (2) This will stop processing on the first object in sys.modules that
> doesn't have a __file__ attribute. Since these objects aren't
> *guaranteed* to be modules, this is a subtle bug waiting to bite you.


In fact, not all modules have a __file__ attribute.


>>> import errno
>>> errno.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'



-- 
Steven



More information about the Python-list mailing list