Python Module Internal Representation and Introspection: Difference between revisions
Line 58: | Line 58: | ||
To check whether <code>__path__</code> exists, use <code>[[Python_Introspection#hasattr.28.29|hasattr()]]</code>. | To check whether <code>__path__</code> exists, use <code>[[Python_Introspection#hasattr.28.29|hasattr()]]</code>. | ||
=Dynamic Module Tree Traversal and Class Loading= | |||
<syntaxhighlight lang='python'> | |||
</syntaxhighlight> |
Revision as of 21:15, 4 January 2023
Internal
Overview
The module Class
All module and package instances are represented internally as instances of the module
class.
Checking whether an Object Instance is a Module
import types
import mymodule
assert isinstance(mymodule, types.ModuleType)
assert not isinstance('something', types.ModuleType)
Attributes
All object instances declared in the module (variables, functions, classes, etc.) become attributes of the module instance and they are accessible with inspect.getmembers()
.
Additionally, the following special attributes are present:
__name__
The __name__
special variable contains the name of the module, when it was imported, as string.
import mymodule
assert mymodule.__name__ == 'mymodule'
When the module is executed directly with python mymodule.py
, it is never imported, so __name__
is set to the "__main__" string.
__file__
Once imported, the file associated with the module can be determined using the module object's __file__
attribute, as string:
import mymodule
[...]
print(mymodule.__file__)
The directory portion of __file__
should be one of the directories in sys.path
.
__doc__
The content of the module docstring, if declared, otherwise None
.
__cached__
__loader__
__spec__
__package__
An empty string for a top-level module, the name of the package for a package or for a module that was loaded as part of a package.
__path__
The __path__
attribute exists only for module
instances that represent packages, not for those instances that represent ordinary modules.
__path__
contains a list of the package root directories, where the component modules, subpackages, __init__.py
and __main__.py
live.
To check whether __path__
exists, use hasattr()
.