How to import a Python class from a directory which has dependency in the same directory?

67 views Asked by At

I want to use a class A, which is in a subdirectory dir in file A.py. It has dependency with file B.py which is also in the same directory dir. I want to use the A class from its parent directory. The file tree looks like this:

parent_dir/
    dir/
        __init__.py (empty file)
        A.py (imports B)
        B.py
    C.py <-- I am here

Content of A:

from B import B

class A:
  def __init__():
    pass

And contents of B:

class B:
  def __init__():
    pass

Now when I try to import A.py from C.py by from dir.A import A, I get:

ModuleNotFoundError                       Traceback (most recent call last)
----> 1 from stargan_v2_tensorflow.networks import Generator

File ~/parent_dir/C.py:1
---> 1 from B import *

ModuleNotFoundError: No module named 'B'

I tried importing B.py by import dir.B as B and from dir import B so that it finds B, but still I get the same error. How can I import A with its dependency?

1

There are 1 answers

2
paime On

It is from .B import B, note the . before B, that's a relative import.

Maybe take a look at the "Relative imports for the billionth time" Stack Overflow post.

Reproduce:

mkdir -p dir
printf '' > dir/__init__.py
printf 'class B: pass' > dir/B.py
printf 'from .B import B\nclass A: pass' > dir/A.py
printf 'from dir.A import A\nprint("SUCCESS")' > C.py
python C.py