First of all: I know that there are many questions and answers on the topic of circular imports.
The answer is more or less: "Correctly create the module / class structure, and you will not need cyclic import." It's true. I tried very hard to make the right project for my current project, I, in my opinion, was successful with this.
But my specific problem is this: I need type checking in a module that is already imported by the module containing the class to check. But this leads to an import error.
Same:
foo.py:
from bar import Bar class Foo(object): def __init__(self): self.__bar = Bar(self)
bar.py:
from foo import Foo class Bar(object): def __init__(self, arg_instance_of_foo): if not isinstance(arg_instance_of_foo, Foo): raise TypeError()
Solution 1: If I changed it to check the type by comparing strings, it will work. But I don't like this solution (string comparison is quite expensive for simple type checking and there may be a problem when it comes to refactoring).
bar_modified.py:
from foo import Foo class Bar(object): def __init__(self, arg_instance_of_foo): if not arg_instance_of_foo.__class__.__name__ == "Foo": raise TypeError()
Solution 2: I could also pack two classes in one module. But in my project there are many different classes, such as "Bar", and I want to split them into different module files.
After my own 2 solutions are not suitable for me: does anyone have a better solution to this problem?
python import circular-dependency
Philip daubmeier
source share