-1

I have a layout like

pylib/
    apps/
        main.py
    libs/
        MyClass.py
    __init__.py

In which MyClass.py is

class MyClass:
    pass


if __name__ == "__name__":
    obj = MyClass()

and in main.py I've tried

from pylib.libs.MyClass import MyClass
obj = MyClass()

And got

ModuleNotFoundError: No module named 'pylib'

from ..libs.MyClass import MyClass
obj = MyClass()

And got

ImportError: attempted relative import with no known parent package

from libs.MyClass import MyClass
obj = MyClass()

And got

ModuleNotFoundError: No module named 'libs'

If someone knows how to fix it I'd be very glad

Gustavo Exel
  • 19
  • 1
  • 6
  • 1
    Does this answer your question? [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) – wetwarebug Feb 12 '20 at 20:45
  • Dis you install your module or add it to PYTHONPATH? – MisterMiyagi Feb 12 '20 at 20:45
  • Note that since there is no ˋpylib/__init__.pyˋ, ˋpylibˋ is a namespace package. This is likely not intentional. Either use ˋlibˋ directly, or add an ˋ__init__.pyˋ. – MisterMiyagi Feb 12 '20 at 20:47

1 Answers1

1

The issue is that the folder that contains pylib is not on the path. You can fix this by adding the containing folder to the PYTHONPATH environment variable.

➜  apps  python3 main.py        
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from pylib.libs.MyClass import MyClass
ModuleNotFoundError: No module named 'pylib'
➜  apps  cd ..
➜  pylib  cd ..
➜  temp-code  export PYTHONPATH=`pwd`  # This is the fix!
➜  apps  python3 main.py        
(no error)

Another way you could do it is to include the logic in your code:

import os
import sys

project_home = '/home/username/temp-code/'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

In this case, the pylib folder is inside of the temp-code folder and this code runs before you import your class.

Hope that helps!

Reference: https://docs.python.org/3/using/cmdline.html?highlight=pythonpath#envvar-PYTHONPATH

C.R.
  • 91
  • 1
  • 3