import语句里面的类/函数定义 - 这是一个好主意吗? [英] Import statement inside class/function definition - is it a good idea?
问题描述
我创建了一个名为 util
的模块,它提供了我经常在Python中使用的类和函数。
其中一些需要导入功能。在类/函数定义中导入需要的东西的优点和缺点是什么?在模块文件的开头是否优于 import
?这是个好主意吗?
I created a module named util
that provides classes and functions I often use in Python.
Some of them need imported features. What are the pros and the cons of importing needed things inside class/function definition? Is it better than import
at the beginning of a module file? Is it a good idea?
推荐答案
这是最常见的风格,的文件。 PEP 8推荐它,这是一个很好的理由做它开始。但这不是一个奇迹,它有优点(虽然不是至关重要,使一切都犯罪)。它允许一目了然地查找所有导入,而不是查看整个文件。它还确保在任何其他代码(可能依赖于某些导入)被执行之前导入一切。 NameError
通常很容易解决,但他们可以讨厌。
It's the most common style to put every import at the top of the file. PEP 8 recommends it, which is a good reason to do it to start with. But that's not a whim, it has advantages (although not critical enough to make everything else a crime). It allows finding all imports at a glance, as opposed to looking through the whole file. It also ensures everything is imported before any other code (which may depend on some imports) is executed. NameError
s are usually easy to resolve, but they can be annoying.
没有通过将模块保持在较小的范围内来避免,因为您添加的是实际模块(否, import *
不计数,可能不应该使用)。在内部函数中,您将在每次调用时重新导入(不是真正有害的,因为一切都导入一次,但不需要)。
There's no (significant) namespace pollution to be avoided by keeping the module in a smaller scope, since all you add is the actual module (no, import *
doesn't count and probably shouldn't be used anyway). Inside functions, you'd import again on every call (not really harmful since everything is imported once, but uncalled for).
这篇关于import语句里面的类/函数定义 - 这是一个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!