Search code examples
pythonimportsys

Import modules from a subfolder


I cannot import modules from a subfolder,where from a subfolder that I am in it; the folders that I work with, is like this:

Project
   __init__.py
   /objects
      __init__.py
      button.py
      text.py
   /menu
      __init__.py
      main_screen.py

I put the __init__.py file in all of the the folders that containt modules; also using the sys.path.insert does not gonna work and I don't know how to handle the problem

I want import button.py and text.py modules from objects folder, while I am in main_screen.py in menu subfolder.

but when I try this in main_screen.py:

from ..objects.button import Button
from ..objects.text import Text

this error occured: ImportError: attempted relative import with no known parent package


Solution

  • when you run main_screen.py, its __name__ attribute is set to '__main__'. This doesn't contain a '.', so relative imports can't be used from here. You can add '.../Project' to sys.path and use absolute imports:

    import sys
    
    sys.path.append('.../Project')
    
    from objects.button import Button
    from objects.text import Text
    

    Alternatively, you can add a __main__.py file to your project path with code like this:

    from menu.main_screen import main
    main()
    

    This assumes your main_screen.py contains a main function. Note that main_screen.py's __name__ attribute will be set to 'menu.main_screen', so if you use an if __name__ == '__main__': construct, it won't be executed.