简体   繁体   English

Python模块是否应该导入其语义上依赖的模块?

[英]Should Python modules import the modules they semantically depend on?

Should Python modules import the modules they semantically depend on? Python模块是否应该import其语义上依赖的模块?

For example: 例如:

module a : 模块a

class A(object):
    ...
    def foo(self):
        ...

module b : 模块b

import a

def f(a_instance):
    a_instance.foo()
    ...

The first line of module b is unnecessary, strictly speaking, but I wonder if it's considered good form in Python? 严格来说,模块b的第一行是不必要的,但是我想知道它是否在Python中被认为是好的形式?

b semantically depends on nothing . b语义上依赖任何内容

quite literally, the only thing that def f depends on is that a_instance produces an attribute .foo that is a callable. 从字面上看, def f唯一依赖的是a_instance产生可调用的属性.foo Full stop. 句号

It doesn't matter if you pass in A() or AChild() or even a MagicMock . 传递A()AChild()甚至是MagicMock

This is what the phrase "duck typing" means. 这就是“鸭子打字”的意思。 Consider: 考虑:

def is_a_duck(duck_candidate):
    duck_candidate.looks_like_a_duck()
    duck_candidate.walks_like_a_duck()
    duck_candidate.quacks_like_a_duck()
    print('This is a duck')
    return True

If you create something that .looks_like_a_duck() , and .walks_like_a_duck() and .quacks_like_a_duck() , then as far as we're concert, it's a duck! 如果创建的内容为.looks_like_a_duck() .walks_like_a_duck().quacks_like_a_duck() ,那么据我们所知,这就是一只鸭子!

class Person:
    def looks_like_a_duck(self): pass
    def walks_like_a_duck(self): pass
    def quacks_like_a_duck(self): pass

class FakeDuck:
    def looks_like_a_duck(self): pass
    def walks_like_a_duck(self): pass
    def quacks_like_a_duck(self): print('Quack quack quack')

def funcy_duck():
    funcy_duck.looks_like_a_duck = lambda: None
    funcy_duck.walks_like_a_duck = lambda: None
    funcy_duck.quacks_like_a_duck = lambda: None
    return funcy_duck

print(is_a_duck(Person())
print(is_a_duck(FakeDuck())

try:
    print(is_a_duck(funcy_duck))
except AttributeError:
    print('not a duck yet')
    funcy_duck()

print(is_a_duck(funcy_duck))

These are all ducks - it doesn't matter if you define them in ducks.py , or different files, or even dump them as pickles and load them up later. 这些都是鸭子-不管是在ducks.py或其他文件中定义它们,还是将它们ducks.py泡菜并稍后加载。 They're all ducks as far as our function is concerned. 就我们的职能而言,它们都是鸭子。 There's no semantic dependencies on anything but what attributes and behavior our argument has. 除了我们的论点具有什么属性和行为外,对任何事物都没有语义依赖性。

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

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