0

I have a directory structure as shown below:

--root
    --common
        util.py
    --submodule
        --common
            util.py
        --code
            a.py
        run.py
    main.py

a.py

from common.util import test_config

main.py

import submodule.a

a.py is importing some code from common module of the submodule. I have added this submodule in root project. the submodule itself works fine when run independently.

When I import a.py in main.py it starts to pick up code from root projects common code instead of the submodule project.

ImportError: cannot import name 'test_config'

I have tried adding sys.path in a.py to force import submodule code but it is not working.

a.py

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir) 

from common.util import test_config

Any help is appreciated

1 Answer 1

2

Your code in a.py should either use a relative import:

from .common.util import test_config

...or a full import path:

from submodule.common.util import test_config
Sign up to request clarification or add additional context in comments.

2 Comments

I added submodule.common.util and init.py in submodule folder but it started causing import issues when running the submodule alone. Using relative import seems like the possible solution here.
If you want to use the submodule in other contexts as well you should explore making it an installable python package instead of just dropping it into different places. If you install it as a library then there will no longer be any confusion about paths for the code in submodule.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.