Impact of PEP-404 on Python Import Statements
The Python Enhancement Proposal (PEP) 404 introduced significant changes to import statements in Python 3, enhancing the clarity and organization of module imports.
What is a Relative Import?
A relative import refers to importing a module from a location relative to the current module or package. In Python 2, implicit relative imports were allowed, but this has been restricted in Python 3.
Changes to Relative Imports
PEP-404 enforces explicit relative imports. Modules must now be imported using the leading . (dot) or .. (double dot) to specify the path relative to the current module's directory. For example:
from .mymodule import MyFunction # Import from within the current package from ..otherpackage import OtherClass # Import from one level up in the directory structure
Restrictions on Star Imports
Star imports (importing all submodules and attributes from a package) are now only permitted at module level code. Previously, star imports were allowed in function and class definitions, but this has been prohibited to prevent namespace pollution and unexpected behavior.
Example:
Python 2 code:
# Function-level star import def my_function(): from mymodule import * do_something_with(MyAttribute) # Class-level star import class MyClass: def __init__(self): from otherpackage import * self.other_variable = OtherVariable
Python 3 code:
# Module-level star import import mymodule do_something_with(mymodule.MyAttribute) # Explicit import within function def my_function(): from mymodule import MyAttribute do_something_with(MyAttribute) # Explicit import within class class MyClass: def __init__(self): from otherpackage import OtherVariable self.other_variable = OtherVariable
By enforcing explicit imports and restricting star imports, Python 3 aims to improve import clarity, reduce namespace collisions, and promote a more structured and maintainable codebase.
The above is the detailed content of How Did PEP 404 Change Python\'s Import Statements?. For more information, please follow other related articles on the PHP Chinese website!