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:
>>> CUSTOM_LOADERS = [MyCustomLoader1, MyCustomLoader2]
>>> type(xml.__loader__) in CUSTOM_LOADERS
True
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 in
STANDARD_LOADERS. This will still have the maintenance issue though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With