词法范围 Python import 语句是不好的做法吗?
Is it bad practice to lexically scope Python import statements?
在 Python 中,import
似乎是真正的词法范围。这是真的吗?
例如,如果您这样做:
def some_function:
import sys
print sys.argv[0]
你会得到一个错误:
Traceback (most recent call last):
File "example.py", line 4, in <module>
print sys.argv[0]
NameError: name 'sys' is not defined
In Perl, use
statements are not lexically scoped, but Perl does not give you a syntax error if you attempt to define them lexically (i.e. within a subroutine). Doing this causes confusion and is considered very bad practice.
在 Python 中,事情似乎并非如此。我相信我已经在某处读到,始终将 import
语句放在代码顶部被认为是一种很好的做法,但是如果它们确实像示例所示那样在词法范围内(意味着它们不能在定义它们的范围之外访问),我不明白为什么将它们放在你使用它们的地方会被认为是不好的做法。
在 Python 中,词法范围 import
s 是不好的做法吗?如果是,请解释原因?
你会找到一个非常好的答案....在这里
Should Python import statements always be at the top of a module?
还没到呢
在 Python 中,import
似乎是真正的词法范围。这是真的吗?
例如,如果您这样做:
def some_function:
import sys
print sys.argv[0]
你会得到一个错误:
Traceback (most recent call last):
File "example.py", line 4, in <module>
print sys.argv[0]
NameError: name 'sys' is not defined
In Perl,
use
statements are not lexically scoped, but Perl does not give you a syntax error if you attempt to define them lexically (i.e. within a subroutine). Doing this causes confusion and is considered very bad practice.
在 Python 中,事情似乎并非如此。我相信我已经在某处读到,始终将 import
语句放在代码顶部被认为是一种很好的做法,但是如果它们确实像示例所示那样在词法范围内(意味着它们不能在定义它们的范围之外访问),我不明白为什么将它们放在你使用它们的地方会被认为是不好的做法。
在 Python 中,词法范围 import
s 是不好的做法吗?如果是,请解释原因?
你会找到一个非常好的答案....在这里 Should Python import statements always be at the top of a module?
还没到呢