[Python-checkins] r47144 - peps/trunk/pep-0338.txt
nick.coghlan
python-checkins at python.org
Wed Jun 28 13:08:51 CEST 2006
Author: nick.coghlan
Date: Wed Jun 28 13:08:51 2006
New Revision: 47144
Modified:
peps/trunk/pep-0338.txt
Log:
Add a note to PEP 338 about the use of relative imports
Modified: peps/trunk/pep-0338.txt
==============================================================================
--- peps/trunk/pep-0338.txt (original)
+++ peps/trunk/pep-0338.txt Wed Jun 28 13:08:51 2006
@@ -180,6 +180,39 @@
and then invokes ``run_module(sys.argv[0], run_name="__main__",
alter_sys=True)``.
+Relative Imports
+================
+
+2.5b1 showed an annoying interaction between this PEP and PEP 328 -
+explicit relative imports don't work from a main module, because
+relative imports rely on ``__name__`` to determine the current module's
+position in the package hierarchy.
+
+Accordingly, the operation of ``run_module()`` was modified so that
+another special variable ``__module_name__`` was defined in the
+namespace of the module being executed. This variable always holds
+the true module name, even if ``__name__`` is set to something else
+(like ``'__main__'``)
+
+Modules that don't rely on relative imports can be used from a
+package as a main module without any changes. In order to both use
+relative imports and also be usable as a main module, a module in a
+package will currently need to use a structure similar to the
+following::
+
+ # Docstring and any future statements
+ _is_main = False
+ if __name__ == "__main__":
+ _is_main = True
+ __name__ = __module_name__
+
+ # Support module section, including relative imports
+
+ if _is_main:
+ # Main module section
+
+That said, Guido's recommended solution is to avoid using relative
+imports in the first place.
Resolved Issues
================
More information about the Python-checkins
mailing list