ImportError - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: ImportError (/thread-23147.html) |
ImportError - fullstop - Dec-13-2019 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 pkg1but if I use, the following, i am getting an ImportError from . import pkg1ImportError: 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 RE: ImportError - Gribouillis - Dec-14-2019 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. RE: ImportError - fullstop - Dec-15-2019 Thanks a lot sir, it clears my doubt thoroughly |