5

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?

korhadris
  • 157
  • 6

1 Answers1

1

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.

korhadris
  • 157
  • 6
  • Thanks. In my case, I can not get CUSTOM_LOADERS list beforehand. STANDARD_LOADERS is better, but it is bit difficult to prepare in standard procedure. >>> import importlib._bootstrap >>> loader_classes = tuple(x[0] for x in importlib._bootstrap._get_supported_file_loaders()) >>> isinstance(os.__loader__, tuple(loader_classes)) True >>> isinstance(sys.__loader__, tuple(loader_classes)) False >>> sys.__loader__ – Takayuki SHIMIZUKAWA Nov 01 '12 at 00:43
  • I think `STANDARD_LOADERS = file_loaders + (BuiltinImporter + FrozenImporter + zipimporter)`. – Takayuki SHIMIZUKAWA Nov 01 '12 at 00:53