问题
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, but they still don't provide enough information for me to get a good understanding of it. All I know is that it has something to do with importing modules, other than that I'm completely at a loss. What does it do? When is it used? How can I use it if at all?
回答1:
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:
__loader__
may be used to gather data on a specific module's loader.In Python versions before 3.3,
__loader__
could be used withhasattr
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 returnedTrue
, it would mean that theos
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.
来源:https://stackoverflow.com/questions/22185888/pythons-loader-what-is-it