python循环导入教程_Python循环导入,“来自lib导入模块”与“ import lib.module”

I have two python modules, a.py and b.py, both of which are in lib/ relative to the current directory. Suppose each module needs the functionality of the other.

a.py:

import lib.b

...

b.py:

import lib.a

...

The above example works with

PYTHONPATH=./lib python -c 'from lib import a, b'

However, if I switch the imports in a.py and b.py to from lib import b and from lib import a, respectively, the above Python command terminates with ImportError.

Could someone please explain why this breaks? I'm not trying to import any member from either a or b. (In that case I would be importing from an uninitialized module, as the question referenced below points out.)

Reference:

解决方案

Since there did not seem to be a direct way to address the circular import, I went with a workaround.

In my actual use case, module a imported module b only to call the function b.fn, so I decided to put fn in a third module c and import c instead:

c.py

def fn():

...

b.py

from lib import a

from lib import c

...

# Explicitly assign `fn` into this module.

fn = c.fn

(The above could also be done with from lib.c import fn, but I prefer the explicit version.)

a.py

from lib import c

...

That way, the circular import between a and b is gone, and any additional modules that import b can use b.fn directly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值