Python Module Internal Representation and Introspection: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 11: Line 11:
==Attributes==
==Attributes==
===<tt>__file__</tt>===
===<tt>__file__</tt>===
Once imported, the file associated with the module can be determined using the module object's __file__ attribute:
Once imported, the file associated with the module can be determined using the module object's <code>__file__</code> attribute:
<syntaxhighlight lang='python'>
<syntaxhighlight lang='python'>
import mymodule
import mymodule
Line 18: Line 18:
</syntaxhighlight>
</syntaxhighlight>
The directory portion of <code>__file__</code> should be one of the directories in <code>[[Python_Language_Modularization#sys.path|sys.path]]</code>.
The directory portion of <code>__file__</code> should be one of the directories in <code>[[Python_Language_Modularization#sys.path|sys.path]]</code>.
===<tt>__path__</tt>===
===<tt>__path__</tt>===
The <code>__path__</code> attribute exists only for <code>module</code> instances that represent [[Python_Language_Modularization#Package|packages]], not for those instances that represent ordinary [[Python_Language_Modularization#Modules|modules]].
The <code>__path__</code> attribute exists only for <code>module</code> instances that represent [[Python_Language_Modularization#Package|packages]], not for those instances that represent ordinary [[Python_Language_Modularization#Modules|modules]].


<code>__path__</code> contains the path of the package root directory, where the component modules, [[Python_Language_Modularization#Subpackages|subpackages]], <code>[[Python_Language_Modularization#init_.py|__init__.py]]</code> and <code>[[Python_Language_Modularization#main_.py|__main__.py]]</code> live.
<code>__path__</code> contains the path of the package root directory, where the component modules, [[Python_Language_Modularization#Subpackages|subpackages]], <code>[[Python_Language_Modularization#init_.py|__init__.py]]</code> and <code>[[Python_Language_Modularization#main_.py|__main__.py]]</code> live.

Revision as of 03:37, 4 January 2023

Internal

Overview

The module Class

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

Attributes

__file__

Once imported, the file associated with the module can be determined using the module object's __file__ attribute:

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.