Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ImportError
#1
I have a directory structure as below:
WD/
main.py
pkg1/
__init__.py
file1.py
file2.py

Now I would like to import pkg1 in my main python code "main.py". I use the following and it works OK
import pkg1
but if I use, the following, i am getting an ImportError
from . import pkg1
ImportError: cannot import name 'pkg1' from '__main__' (main.py)

On the other hand, I don't get an error if I use the same syntax for importing a module
For example, if I use the following in __init__.py file
from . import file1.py
Reply
#2
When it meets the statement
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.
Reply
#3
Thanks a lot sir, it clears my doubt thoroughly
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020