Python's __loader__, what is it?

前端 未结 1 1813
广开言路
广开言路 2021-02-13 05:41

I\'ve seen the term __loader__ floating around some Python files and I can\'t find any documentation on it aside from a few brief descriptions about it\'s purpose,

相关标签:
1条回答
  • 2021-02-13 06:05

    What is __loader__?

    __loader__ is an attribute that is set on an imported module by its loader. Accessing it should return the loader object itself.

    In Python versions before 3.3, __loader__ was not set by the built-in import machinery. Instead, this attribute was only available on modules that were imported using a custom loader.

    However, this functionality changed in Python 3.3 because of PEP 0302. Now, __loader__ is available on every module that is imported:

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

    What is a loader?

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


    What is a finder?

    A finder is an object that uses its find_module() method to try and find the loader for a module. importlib.abc.Finder is an example of an abstract base class for a finder. 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:

    1. __loader__ may be used to gather data on a specific module's loader.

    2. In Python versions before 3.3, __loader__ could be used with hasattr to check whether or not a module was imported with the built-in import machinery:

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

      If hasattr(os, '__loader__') had returned True, it would mean that the os module was imported using a custom loader. Since it did not, it means that the module was imported using the built-in import machinery.

      Note: The above test will not work in Python 3.3+ because of the changes made by PEP 0302.

    0 讨论(0)
提交回复
热议问题