Suppose you have the following level pack directories
Project/__init__.pyMyPackage/__init__.pyA/__init__.pyspam.py #* print ("in spam") *#Grok.py #* Print ("in Grok") *#C/__init__.pyHello.py #* print ("in Hello") *#B/__init__.pyBar.py #* Print ("in Bar") *#Run.pyMain.py
Relative Import Syntax
from . Import Module from .. Import Module from ... Import ModuleRelative import is related to module __name__
- run.py when importing A.spam as a top-level module
- Run.py's __name__ equals __main__.
- Spam.py's __name__ equals A.spam.
- A becomes the top-level package, so the relative import is the most? only access to hierarchies outside of A,a is not visible
- main.py as the top-level module to perform the import Mypackage.a.spam is
- The __name__ of main.py is __main__
- The __name__ of spam.py is mypackage. A.spam
- MyPackage becomes the top-level package, relative import scope expands, b/package to spam.py visible
Relative import applies only to modules in the package, which will not work in the top-level module
- If you use run.py as the top-level execution module
- A/and B/will become TopLevel modules in Package top-level packages A/are not able to import modules in A/package with relative imports because they cannot cross the top-level package.
- A/, B/package directory can be imported into the package and the following modules
- If you use main.py as the top-level execution module
- mypackage/becomes the top level package, A/can access to B/pack, does not appear valueerror:attempted relative import beyond top-level packages
Example"' run.py Import A.spam " "-----------------------------------"' spam.py From . Import Grok # OKFrom . C Import Hello # OKFrom .. B Import Bar #! ERR < c10> -- valueerror:attempted relative import beyond top-level packageprint (' in spam ') " ""' main.py import MyPackage. A.spam " "-----------------------------------"' spam.py From .. B Import Bar # OKprint (' in spam ') " "
Python Relative Import