Python Module Internal Representation and Introspection: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 17: Line 17:
<syntaxhighlight lang='python'>
<syntaxhighlight lang='python'>
import mymodule
import mymodule
[...]
assert mymodule.__name__ == 'mymodule'
print(mymodule.__name__)
</syntaxhighlight>
</syntaxhighlight>
===<tt>__file__</tt>===
===<tt>__file__</tt>===
Once imported, the file associated with the module can be determined using the module object's <code>__file__</code> attribute, as string:
Once imported, the file associated with the module can be determined using the module object's <code>__file__</code> attribute, as string:

Revision as of 03:46, 4 January 2023

Internal

Overview

The module Class

All module and package instances are represented internally as instances of the module class.

Attributes

All object instances declared in the module (variables, functions, etc.) become attributes of the module instance and they are accessible with inspect.getmembers(). Additionally, the following special attributes are present:

__name__

The name of the module, as string.

import mymodule
assert mymodule.__name__ == 'mymodule'

__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.

__path__

The __path__ attribute exists only for module instances that represent packages, not for those instances that represent ordinary modules.

__path__ contains the path of the package root directory, where the component modules, subpackages, __init__.py and __main__.py live.