vgbcell
vgbcell

Reputation: 199

Pythonic Way to structure module API with circular import

How should I resolve the following circular dependency?

I have a file A that exposes API methods and delegates all the backend logic to a separate file, A_impl.

In A.py, I also expose an Enum which clients need to pass in as an argument to some of the API methods:

# A.py
import A_impl

class MyEnum(Enum):
    ONE = 1
    TWO = 2
    THREE = 3

def A(x: MyEnum):
    return A_impl._A(x)

A_impl actually needs MyEnum:

#A_impl.py
from A import MyEnum

def _A(x: MyEnum):
    pass

One way to resolve this is to just merge the two modules together but that defeats the purpose of splitting it up for cleaner code in the first place. A_impl consists of dozens of helper functions and putting the public and private methods into one module was getting messy.

Upvotes: 0

Views: 70

Answers (1)

blhsing
blhsing

Reputation: 106863

You can import A_impl inside the definition of A instead:

# A.py

class MyEnum(Enum):
    ONE = 1
    TWO = 2
    THREE = 3

def A(x: MyEnum):
    import A_impl
    return A_impl._A(x)

Upvotes: 3

Related Questions