Skip to content Skip to sidebar Skip to footer

Python Circular Import, `from Lib Import Module` Vs `import Lib.module`

I have two python modules, a.py and b.py, both of which are in lib/ relative to the current directory. Suppose each module needs the functionality of the other. a.py: import lib.b

Solution 1:

Since there did not seem to be a direct way to address the circular import, I went with a workaround.

In my actual use case, module a imported module b only to call the function b.fn, so I decided to put fn in a third module c and import c instead:

c.py

def fn():
  ...

b.py

fromlib import a
fromlib import c
...
# Explicitly assign `fn` into this module.
fn = c.fn

(The above could also be done with from lib.c import fn, but I prefer the explicit version.)

a.py

from lib import c
...

That way, the circular import between a and b is gone, and any additional modules that import b can use b.fn directly.

Solution 2:

in your lib folder there is a __init__.py file? If yes you have 2 possibility:

1) __init__.py is empty and you can use from lib import a,b

a.foo b.bar

2) in your __init__.py there are istructions import a,b in this case you can write

import lib.a as a import lib.b as b

hope this help you

Post a Comment for "Python Circular Import, `from Lib Import Module` Vs `import Lib.module`"