Reputation: 71
How do I import a class from a lower-level directory in python?
I've been reading about how I should add __init__.py
to my folders (or is this only in python2?) or how I should use from __future__.py import absolute_import
, but none of those work.
With the code below I get: ValueError: attempted relative import beyond top-level package
Also I've tried importing like from .folder2.file2 import Class2
, which gives the error: ModuleNotFoundError: No module named '__main__.folder2'; '__main__' is not a package
main.py
from folder1.file1 import Class1
if __name__ == "__main__":
Class1()
file1.py
from ..folder2.file2 import Class2
class Class1:
def __init__(self):
print("Foo")
Class2()
file2.py
class Class2:
def __init__(self):
print("Bar")
Thank you.
Upvotes: 1
Views: 491
Reputation: 590
Yeah, you'll need to add an __init__.py
to all of the folders Python needs to look through (regardless of your python version), i.e. if you have a structure like this:
importing
- folder1
-- file1.py
- folder2
--file2.py
- main.py
you'll want it to end up looking something like this:
importing
- __init__.py
- folder1
-- __init__.py
-- file1.py
- folder2
-- __init__.py
--file2.py
- main.py
i.e. you need an __init__.py
in folder1
, folder2
, and importing
Upvotes: 1