I have a directory and module design that looks like this:
MyProject --- - script.py
|
- helpers --- - __init__.py
|
- class_container.py
|
- helper.py
# class_container.py
class MyClass:
pass
# helper.py
from class_container import MyClass
def func():
# some code using MyClass
# script.py
from helpers.helper import func
When I run script.py
:
ModuleNotFoundError: No module named 'class_container'
I tried changing the code in helper.py
such as:
# helper.py
from helpers.class_container import MyClass
def func():
# some code using MyClass
Then running script.py
started working. But when I explicitly run helper.py
:
ModuleNotFoundError: No module named 'helpers'
I want to be able run both script.py
and helper.py
separately without needing to change the code in any module.
Edit: I figured a solution which is changing helper.py
such as:
from pathlib import Path
import sys
sys.path.append(str(Path(__file__).parent))
from class_container import MyClass
def func():
# some code using MyClass
Basically I added the directory of helper.py
to sys.path
by using sys
and pathlib
modules and __file__
object. And unlike import
statement's behaviour, __file__
will not forget it's roots when imported/used from a different module (i.e it won't become the path of script.py
when imported into it. It'll always be the path of helper.py
since it was initiated there.).
Though I'd appreciate if someone can show another way that doesn't involve messing with sys.path
, it feels like an illegal, 'unpythonic' tool.