ImportError:How to import function or class from parent directory

Viewed 37

I am trying to import a class from parent directory to my script but I receive attempted relative import with no known parent packageerror, I have searched everywhere in the internet but still cannot fix the error. Here is my package structure:

A/
  a.py
  __init__.py
  B/
    __init__.py
    c.py

Now assume I have class1 inside a.py module and I am trying to import it in the c.py module. I have tried:

from ..A.a import class1

But i get above error message I have tried to add the A folder to sys.path but still the same error. Can anyone explain how I can import a package from a function or class from parent directory to subdirectory (like from a.py to c.py)

1 Answers

The way I do this is my extending the path in the c.py file by appending it. Below is an example of this:

a.py (example module in the parent directory)

class class1:
    def __init__(self):
        print("This worked!")

c.py (example file invoking a.py in the parent directory)

# By importing the sys module, you can change many
# things including the system environment.
import sys
sys.path.append("../")

# Once you've added the parent directory, you can freely
# import as you would have normally.
from a import class1
instance = class1() 

The reason why your .. didn't work is because imports starting with . or .. are for importing from within things being imported (the way I understand it). An example of this to use your example would be to add a d.py alongside a.py which could be imported from a.py by using from .d import *.

Related