Python __loader__, what is it?

I saw the term __loader__ floating around some Python files, and I can not find any documentation for it, except for a few brief descriptions about this purpose, but they still do not provide enough information for me to have a good understanding of this. All I know is that it has something to do with importing modules, except that I'm completely at a loss. What does it do? When is it used? How can I use it, if at all?

+6
source share
1 answer

What is __loader__ ?

__loader__ is an attribute that is installed on an imported module by its loader. Access to it should return the loader object itself.

In versions of Python prior to 3.3, __loader__ not installed by the built-in import mechanism. Instead, this attribute is only available in modules that have been imported using a custom loader.

However, this functionality has changed in Python 3.3 due to PEP 0302 . Now __loader__ is available for each imported module:

 >>> # Python 3.3 interpreter >>> import os >>> os.__loader__ <_frozen_importlib.SourceFileLoader object at 0x01F86370> >>> 

What is a bootloader?

A loader is an object that is returned by the crawler. It uses its load_module() method to load the module into memory. importlib.abc.Loader is an example of an abstract base class for the loader.


What is a search engine?

A finder is an object that uses its find_module() method to find the loader for the module. importlib.abc.Finder is an example of an abstract base class for a crawler. Note, however, that it is deprecated in favor of importlib.abc.MetaPathFinder and importlib.abc.PathEntryFinder .


How can I use it, if at all?

The main use of __loader__ is for introspection. However, there are two other common uses:

  • __loader__ can be used to collect data on a specific module loader.

  • In versions of Python prior to 3.3, __loader__ can be used with hasattr to check whether a module with a built-in import mechanism has been imported:

     >>> # Python 3.2 interpreter >>> import os >>> hasattr(os, '__loader__') False >>> 

    If hasattr(os, '__loader__') returned True , this would mean that the os module was imported using a custom loader. Since this is not the case, this means that the module was imported using the built-in import mechanism.

    Note. The above test will not work in Python 3.3+ due to changes made by PEP 0302.

+9
source

All Articles