How do I make imports work for file that need to be called from different folders?

Question:

This is my folder structure

├── folder1
│   ├── component.py
│   └── utils
│       └── utils.py
└── rootComponent.py

component.py makes use of utils. So I import it with

import utils

but if I try to import component.py from rootComponent.py

import folder1.component

I get ModuleNotFoundError: No module named 'utils'

If I change the way I import utils in component.py to

import folder1.utils

Then it works from rootComponent.py, but it stops working from component.py, when I run it on its own

How can I import utils in component.py so that it works both if I run the script on its own or if I import it from rootComponent.py?

Asked By: BaridunDuskhide

||

Answers:

an ad-hoc and dirty solution can be done with a try-except block:

# in component.py
try:
    import utils
except:
    import folder1.utils

another solution is to modify the sys.path. python searches paths listed here for import requests after it searched the current folder and python’s standard library. hence, by adding the folder1 to this list, we can import any of its contents, independent from the script’s execution path (as long as there is no name collision though)

# in rootComponent.py
import sys

sys.path.append('folder1') # but this path is relative. if you want absolute independence, provide the full path from the root.

import component, utils
Answered By: Dariush Mazlumi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.