简体   繁体   中英

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

Let's say I have module child :

# child.py

import numpy as np
import parent

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

Then in 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? 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.

I would re-import numpy where you suggest in parent.py . For justification I refer you to 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. The following is even more explicit that A should be a numpy matrix:

# parent.py

import numpy an np

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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