Add a note to PEP 338 about the use of relative imports

This commit is contained in:
Nick Coghlan 2006-06-28 11:08:51 +00:00
parent 4939886cb8
commit f4ddb4ef6e
1 changed files with 33 additions and 0 deletions

View File

@ -180,6 +180,39 @@ deleting ``sys.argv[0]`` (which refers to the ``runpy`` module itself)
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
================