What is the right way in Python to import a module from a directory one level up? The directory is a Python package with all these modules and I have a sub directory with code that needs these modules.
The following works just fine, but that is just a hack. I'd like a recommended / pythonic way.
import sys
sys.path.append("../")
from fruit import Fruit
print("OK")
The directory structure:
pkg1
__init__.py
fruit.py
+sub_pkg
__init__.py
recipe.py
contents of fruit.py
class Fruit:
def get_name(self):
print("Fruit name")
contents of sub_pkg/recipe.py
.. just a single import line:
from fruit import Fruit
When I run :
python recipe.py
it gives the following error.
Traceback (most recent call last):
File "recipe.py", line 2, in <module>
from fruit import Fruit
ImportError: No module named fruit
I also tried: from pkg1.fruit import Fruit
, does not work. Also looked at other similar questions ..
python -m recipe.py
or python -m sub_pkg/recipe.py
did not work.