0

If I have the files frame.py and bindings.py both with classes Frame and Bindings respectively inside of them, I import the bindings.py file into frame.py by using from bindings import Bindings but how do I go about importing the frame.py file into my bindings.py file. If I use import frame or from frame import Frame I get the error ImportError: cannot import name 'Bindings' from 'bindings'. Is there any way around this without restructuring my code?

hcphoon
  • 538
  • 5
  • 24
  • 1
    [Two Python modules require each other's contents - can that work?](https://stackoverflow.com/a/11698542/8146707) – Varada Mar 19 '19 at 09:14

2 Answers2

0

Instead of using from bindings import Bindings try import bindings.

Francesco Pegoraro
  • 778
  • 13
  • 33
0

This is what we call circular import. Let's look at the example. We have the two files:

frame.py

from bindings import Bindings

class Frame:
    pass

bindings.py

class Bindings:
    pass

print("class Binding here")

from Frame import Frame

First thing you should know is, whenever we import a file, the code in the file we're importing is also executed at the same time. So in my example, when you run the frame.py file, it first executes the bindings.py file, where it will also find what it's looking for (i.e. class Bindings). And while the bindings.py files is being executed, the from Frame import Frame line will then execute the frame.py file, getting what it wants (i.e. class Frame).

Rabin Lama Dong
  • 2,422
  • 1
  • 27
  • 33