Search code examples
python-3.xrelative-import

Is it possible to fix problems with relative imports?


I have some problems with import mechanic. For example I have a tree like this:

├── my_package  
|   ├── first.py  
|   └── second.py  
└── test.py

second.py:

def second_func():
    print('Hello World')

first.py:

from second import second_func

def first_func():
    second_func()

test.py:

from my_package.first import first_func

first_func()

And when I try to run test.py I get this error:

ModuleNotFoundError: No module named 'second'

It feels like second.py is not searched in my_package, but in the directory where my_pacakage and test.py are located. This is a strange mechanics, because if I have a ready-made package, I don’t want to create some new file in it, I want to interact with it from another place.


Solution

  • First create a __init__.py in the my_package. Change import statement of the first.py to the following

    from .second import second_func

    Then run python test.py. It should give Hello World