简体   繁体   English

使用循环导入的Pythonic方法来构建模块API

[英]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. 我有一个文件A,它公开API方法并将所有后端逻辑委托给一个单独的文件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中,我还公开了一个枚举,客户端需要将该枚举作为参数传递给某些API方法:

# 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实际上需要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. A_impl由数十个辅助函数组成,将公共方法和私有方法放在一个模块中变得一团糟。

You can import A_impl inside the definition of A instead: 您可以在A的定义内导入A_impl

# A.py

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM