简体   繁体   English

从定义符号的模块中导入还是从直接导入的模块中导入,是哪一种更好?

[英]Which one is preferred, importing from module where a symbol is defined or from the module imported directly?

Given in the example below, symbol A is defined in module a and imported in b. 在下面的示例中给出,符号A在模块a中定义,并在b中导入。 Module c imports b. 模块c导入b。 Should it access A from module a directly or get it from B (the module it imported directly)? 它应该直接从模块a访问A还是从模块B(直接导入的模块)获取它? I am thinking of the latter so that I don't need to worry about removing direct references to A, if some day I retire references to b from module c. 我正在考虑使用后者,因此,如果有一天我从模块c中撤消了对b的引用,那么我就不必担心删除对A的直接引用。

a.py a.py

def A(Exception):
    pass

def funA():
    raise A

b.py b.py

from a import A, funA

def funB():
    try:
        funA()
    except A as e:
        # some additional handling
        raise

c.py c.py

import b

# Which of the following is preferred?
# 1. 
try:
    funB():
except a.A:
    # do something

# 2. 
try:
    funB():
except b.A:
    # do something

I recommend the former because: 我推荐前者,因为:

  • The latter is misleading about the origin of the function. 后者误导了函数的来源。
  • Using the latter reduces maintainability as you need to traverse b when looking for the function's definition - only to find that it resides in a. 使用后者会降低可维护性,因为在查找函数的定义时需要遍历b-只是发现它位于a中。
  • Moreover, in case you decide to drop module B and directly import A, your code will break. 此外,如果您决定删除模块B并直接导入A,则代码将中断。

However, at the end of the day, it boils down to what you and your team prefer. 但是,归根结底,这归结为您和您的团队所喜欢的。 Regardless of what you choose, I recommend that you stay consistent with the choice. 无论您选择什么,我都建议您保持选择的一致性。

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

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