Circular Import

Chris Angelico rosuav at gmail.com
Tue Apr 12 13:47:41 EDT 2022


On Wed, 13 Apr 2022 at 03:37, Stefano Ovus <stefano.ovus at gmail.com> wrote:
>
> found a solution: importing modules instead of classes, ex.
>
> -- square.py
>
> import circle
>
> ...
> @classmethod
>   def from_circle(cls, circle: circle.Circle) -> Square:
>     ...
>     return cls(...)

Yep! Good solution.

Be aware that this will only work if both modules have fully executed
before the references are actually needed. Usually not a problem, but
if you have code that runs at top-level that needs to refer to the
other module (as opposed to simply defining classes and methods, where
those methods are going to refer to the other module when they get
called), it might not work. But that's no different from any other
circular dependency.

ChrisA


More information about the Python-list mailing list