Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b5a3d9b

Browse files
committed
Issue #24029: Document the name binding behavior for submodule imports.
2 parents 532af16 + 4e1f355 commit b5a3d9b

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

Doc/reference/import.rst

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,41 @@ import machinery will create the new module itself.
468468
``create_module()`` is not. Starting in Python 3.6 it will be an error to not
469469
define ``create_module()`` on a loader attached to a ModuleSpec.
470470

471+
Submodules
472+
----------
473+
474+
When a submodule is loaded using any mechanism (e.g. ``importlib`` APIs, the
475+
``import`` or ``import-from`` statements, or built-in ``__import__()``) a
476+
binding is placed in the parent module's namespace to the submodule object.
477+
For example, if package ``spam`` has a submodule ``foo``, after importing
478+
``spam.foo``, ``spam`` will have an attribute ``foo`` which is bound to the
479+
submodule. Let's say you have the following directory structure::
480+
481+
spam/
482+
__init__.py
483+
foo.py
484+
bar.py
485+
486+
and ``spam/__init__.py`` has the following lines in it::
487+
488+
from .foo import Foo
489+
from .bar import Bar
490+
491+
then executing the following puts a name binding to ``foo`` and ``bar`` in the
492+
``spam`` module::
493+
494+
>>> import spam
495+
>>> spam.foo
496+
<module 'spam.foo' from '/tmp/imports/spam/foo.py'>
497+
>>> spam.bar
498+
<module 'spam.bar' from '/tmp/imports/spam/bar.py'>
499+
500+
Given Python's familiar name binding rules this might seem surprising, but
501+
it's actually a fundamental feature of the import system. The invariant
502+
holding is that if you have ``sys.modules['spam']`` and
503+
``sys.modules['spam.foo']`` (as you would after the above import), the latter
504+
must appear as the ``foo`` attribute of the former.
505+
471506
Module spec
472507
-----------
473508

Misc/NEWS

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ Library
3636
- Issue #23887: urllib.error.HTTPError now has a proper repr() representation.
3737
Patch by Berker Peksag.
3838

39+
Documentation
40+
-------------
41+
42+
- Issue #24029: Document the name binding behavior for submodule imports.
43+
3944

4045
What's New in Python 3.5.0 alpha 4?
4146
===================================

0 commit comments

Comments
 (0)