3

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)

user59419
  • 893
  • 8
  • 20
  • The short version is that the `A` folder needs to be in the list of paths that Python searches for modules and packages. Please see the linked duplicate for a thorough overview. – Karl Knechtel Jul 07 '22 at 07:26

1 Answers1

0

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 *.

Jack Hales
  • 1,574
  • 23
  • 51
  • It did not work it says ImportError: attempted relative import with no known parent package. is it different if I am running it in jupyter notebook like c.ipynb – user59419 Jul 07 '22 at 07:02
  • @user59419 did you try changing `from ..A.a import class1` to `from a import class1` ?? – Jack Hales Jul 07 '22 at 07:04
  • Yes, absolutely – user59419 Jul 07 '22 at 07:05
  • If you can try running it in a script to make sure it works that'll help. Also make sure you're running all the blocks and re-running them @user59419 - it's hard to offer any advice outside of "make sure the environment is ok" since that path error means the same code is running and you haven't changed it – Jack Hales Jul 07 '22 at 07:09