Before Python-3.3, I detected that a module was loaded by a custom loader with hasattr(mod, '__loader__').
After Python-3.3, all modules have the __loader__ attribute regardless of being loaded by a custom loader.
Python-2.7, 3.2:
>>> import xml
>>> hasattr(xml, '__loader__')
False
Python-3.3:
>>> import xml
>>> hasattr(xml, '__loader__')
True
>>> xml.__loader__
<_frozen_importlib.SourceFileLoader object at ...>
How do I detect that a module was loaded by a custom loader?
The simple check for the existence of the
__loader__attribute is no longer sufficient in Python 3.3. PEP 302 requires that all loaders store their information in the__loader__attribute of a module.I would add an additional check for the
type(module.__loader__)to see if the module was loaded with the custom loader (or in a list of loaders) you are searching for:This may be bad from a maintenance point-of-view, in that you will have to keep the list of custom loaders up to date. Another similar approach may be creating a list of the standard built-in loaders and change the check to be
not inSTANDARD_LOADERS. This will still have the maintenance issue though.