Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve circular import error in python [duplicate]

Possible Duplicate:
Circular (or cyclic) imports in Python

I have class B that imports and creates instances of class A. Class A needs reference to B in its contructor and so includes B.

from a import A
class B:
  def __init__(self):
    self.a = A()

from b import B
class A:
  def __init__(self, ref):
    assert isinstance(ref, B)
    self.ref = ref

This doesn't work. The main file imports B and uses it... not. Something with the imports is wrong.

Error from file a ImportError: cannot import name B

like image 434
HWende Avatar asked Apr 05 '12 10:04

HWende


People also ask

What is __ all __ in Python?

Python __all__ It's a list of public objects of that module, as interpreted by import * . It overrides the default of hiding everything that begins with an underscore.

What is circular dependency in Python?

In software engineering, a circular dependency is a relation between two or more modules which either directly or indirectly depend on each other to function properly. Such modules are also known as mutually recursive.


2 Answers

Apart from "don't do that, you are painting yourself into a corner", you could also postpone the import of B until you need it. File a.py:

class A:
    def __init__(self, ref):
        from b import B
        assert isinstance(ref, B)
        self.ref = ref

Class B won't be imported until you instantiate class A, by which time the module already has been imported fully by module b.

You can also use a common base class and test for that.

like image 134
Martijn Pieters Avatar answered Oct 08 '22 13:10

Martijn Pieters


Just import classes in __init__ method

class A:
   def __init__(self, ref):
      from b import B
      assert isinstance(ref, B)
      self.ref = ref
like image 36
Ildus Avatar answered Oct 08 '22 13:10

Ildus