简体   繁体   中英

attempted relative import beyond top-level package python

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

Directory structure

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.

Yeah, you'll need to add an __init__.py to all of the folders Python needs to look through (regardless of your python version), ie 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

ie you need an __init__.py in folder1 , folder2 , and importing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM