简体   繁体   English

在父子模块中导入祖父母模块的Python最佳实践

[英]Python best practice for importing grandparent module in parent and child modules

Let's say I have module child : 假设我有模块child

# child.py

import numpy as np
import parent

parent.do_stuff(A = np.array([1,2,3]))

Then in parent : 然后在parent

# parent.py

# Should I import numpy here?

def do_stuff(A):
    print A.T

My question is, do I import numpy in parent , even though I know it should not be used as a standalone module? 我的问题是,即使知道不应该将numpy用作独立模块,我也可以在parent导入numpy吗? I prefer to re- import numpy because it is clear that A is a numpy array rather than a Python list but it also doesn't seem DRY. 我更喜欢重新import numpy因为很明显A是一个numpy array而不是Python list但它似乎也不是DRY。

I would re-import numpy where you suggest in parent.py . 我将在您在parent.py建议的地方重新导入numpy。 For justification I refer you to PEP 20: 出于正当理由,请您参考PEP 20:

Explicit is better than implicit 显式胜于隐式

Simple is better than complex 简单胜于复杂

Certainly re-importing numpy makes it clear what you expect A to be. 当然,重新导入numpy可以使您清楚地期望A是什么。 The following is even more explicit that A should be a numpy matrix: 以下更明确地表明A应该是一个numpy矩阵:

# parent.py

import numpy an np

def do_stuff(A):
    print np.transpose(A)

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

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