Featurecore
Importing from a package
Also called from package import *, __all__, star import from a package, from package import submodule, wildcard import.
from package import * imports the submodules listed in the __all__ of the __init__.py file. Without __all__, it binds only the names that the package already has.
- Language
- Python
Synopsis
# effects/__init__.py
__all__ = ["echo", "surround"] # what from effects import * loads
from effects import * # imports effects.echo and effects.surround
from effects import echo # one submodule: the recommended form
from effects.echo import echofilter
Semantics
r1. from package import item accepts a submodule or any other name: "the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised."1 Example: specific.
r2. The star form does not search the directory for submodules. The tutorial explains why: "This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported."1
r3. The package gives the list in __all__: "if a package’s init.py code defines a list named all, it is taken to be the list of module names that should be imported when from package import * is encountered."1 The reference adds that "The names given in all are all considered public and are required to exist."2 Example: with-all.
r4. "If all is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in init.py) and then imports whatever names are defined in the package."1 That includes "any submodules of the package that were explicitly loaded by previous import statements."1 Example: without-all.
r5. A name in the __init__.py file wins over a submodule with the same name. "Be aware that submodules might become shadowed by locally defined names."1 Example: shadowed.
r6. The tutorial advises against the star form: "it is still considered bad practice in production code. Remember, there is nothing wrong with using from package import specific_submodule! In fact, this is the recommended notation unless the importing module needs to use submodules with the same name from different packages."1
Examples
__all__ names two of the three submodules, so the star import loads those two (rule r3). reverse does not load.
__all__ = ["echo", "surround"]
print("load echo")
print("load surround")
print("load reverse")
from effects import *
print(sorted(n for n in globals() if not n.startswith("__")))
load echo
load surround
['echo', 'surround']
Without __all__, the star import binds the names of __init__.py that do not start with an underscore, and the submodules that are already loaded (rule r4). Here echo was loaded before, and surround was not.
VERSION = "1.0"
_cache = {}
print("load echo")
print("load surround")
import effects.echo
from effects import *
print(sorted(n for n in globals() if not n.startswith("__")))
load echo
['VERSION', 'echo', 'effects']
The case from the tutorial: __init__.py defines a function reverse, so the star import binds the function, and the submodule reverse does not load (rule r5).
__all__ = ["echo", "reverse"]
def reverse(msg):
return msg[::-1]
print("load echo")
print("load reverse")
import sys
from effects import *
print(reverse("abc"))
print("effects.reverse" in sys.modules)
load echo
cba
False
The recommended form names the submodule or the function (rules r1 and r6).
"""Sound effects."""
def echofilter(text):
return text + " " + text[-2:]
from effects import echo
from effects.echo import echofilter
print(echo.echofilter("hello"))
print(echofilter is echo.echofilter)
hello lo
True
The examples give the same output on CPython 3.12.3, 3.13.14 and 3.14.6.
Pitfalls
A name in __all__ that does not exist
The names in __all__ "are required to exist" (rule r3). A name that is neither defined in __init__.py nor a submodule makes the star import fail.
__all__ = ["echo", "flanger"]
print("load echo")
This code raises AttributeError, on purpose.
from effects import *
The tutorial says: "It is up to the package author to keep this list up-to-date when a new version of the package is released."1
Expecting the star form to load all submodules
Without __all__, a submodule that nothing has imported yet is not bound (rule r4). The result then depends on what other code imported before. Name the submodules you use.
__all__ and the public interface
PEP 8 connects __all__ with the public interface: "To better support introspection, modules should explicitly declare the names in their public API using the all attribute."3 A star import is still not a good way to use that interface: "Wildcard imports (from import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools."3
Comparison
Java has an on-demand import, import PackageOrTypeName . * ;, that "allows all accessible classes and interfaces of a named package, class, or interface to be imported as needed."4 The Python star form instead runs the code of each submodule in __all__ when the statement executes, as in with-all.
Rust has the glob form use std::collections::*;, which "brings all public items defined in std::collections into the current scope."5 The book gives the same warning as the Python tutorial: "Glob can make it harder to tell what names are in scope and where a name used in your program was defined."5
Implementation notes
The from form of the import statement checks for an attribute first and then tries to import a submodule with that name (rule r1).2 The star form follows the same order for the names in __all__. In shadowed, the attribute reverse exists, so CPython never loads the submodule effects.reverse.
References
- The Python Tutorial, 6. Modules, 6.4. Packages; 6.4.1. Importing * From a Package
- The Python Language Reference, 7. Simple statements, 7.11. The import statement
- PEP 8: Style Guide for Python Code, Imports; Public and Internal Interfaces
- The Java Language Specification, Java SE 25 Edition, Chapter 7. Packages and Modules, 7.5.2. Type-Import-on-Demand Declarations
- The Rust Programming Language, 7.4. Bringing Paths into Scope with the use Keyword, The Glob Operator
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 1DDM2N Edit this page History Report an error Markdown