Dec-14-2019, 04:50 PM
(This post was last modified: Dec-14-2019, 05:14 PM by Gribouillis.)
When it meets the statement
python looks at the value of the
In the main program that is executed, the value of the
In your example, within the files
In any case, remember that the dot in relative import statements is not a reference to the hierarchy of files and directories, it is a reference to the hierarchy of python modules and packages, which is a related but different thing.
from . import file1
python looks at the value of the
__package__
variable. Normally this variable is a dotted path such as 'foo.bar.baz'
. In that case, if foo.bar.baz.file1
has not already been imported, python will look at sys.modules['foo.bar.baz'].__path__
which is a sequence of directories where it tries to find the file file1.py
, or a subdirectory named file1
(this is only the basic scheme, there are many many special cases in the import mechanism).In the main program that is executed, the value of the
__package__
variable is None
, therefore python cannot execute relative imports from here. (actually PEP 366 explains that you could yourself update this variable to the path of an already imported package to make relative imports possible but this is not for begginers).In your example, within the files
__init__.py
or file1.py
or file2.py
, the value of __package__
is 'pkg1'
, hence, relative imports are possible from these files.In any case, remember that the dot in relative import statements is not a reference to the hierarchy of files and directories, it is a reference to the hierarchy of python modules and packages, which is a related but different thing.