类/函数定义中的导入语句 - 这是一个好主意吗? [英] 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?
推荐答案
将 every 导入放在文件顶部是最常见的样式.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).
这篇关于类/函数定义中的导入语句 - 这是一个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!