Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How do you detect that a module has been loaded by custom loader?

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?

like image 716
Takayuki SHIMIZUKAWA Avatar asked Nov 13 '22 18:11

Takayuki SHIMIZUKAWA


1 Answers

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.

like image 180
korhadris Avatar answered Nov 15 '22 11:11

korhadris