Home python ImportError: attempted relative import with no known parent package python

ImportError: attempted relative import with no known parent package python

Author

Date

Category

At me here such project structure
— package1 / code.py
— package2 / ext.py

How do I import a variable from ext.py in code.py?

from ext import var – does not work, says that there is no module ext

from ..package2.ext import var – also does not work get an error: ImportError: attempted relative import with no known parent package


Answer 1, Authority 100%

Python scans a list of directories specified in the sys.path .

Error: ImportError: attempted relative import with no known parent package indicates that the module has not been found in the sys.path (the output of its print will help to clarify the situation) .

With this structure, it is desirable to use main.py to start import and child modules:

project_folder /
  main.py
  package1 /
   __init__.py
   code.py
  package2 /
   __init__.py
   ext.py

If you need to run code.py and at the same time to import data from ext.py , you need to:

  • run code.py as a module python -m package1.code
  • or add sys.path.append (os.getcwd ()) to the beginning code.py

Answer 2

  • in packages package1 and package2 must be an empty file __ init __. Py (if it is not)
  • Such a structure would be:
vash_proekt /
  package1 /
   __init__.py
   code.py
  package2 /
   __init__.py
   ext.py
  • I tested on these files:

code.py

var = "code.py"

ext.py

from package1.code import var
print (var) # prints code.py

p.s. I hope something helped

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions