如果我在一个函数中导​​入一个模块,变量会是局部的吗?

If I import a module inside a function, will the variables be local?

如果我在函数(本地范围)内导入 python 3 中的模块,导入的内容是否对函数而言是本地的?

喜欢

def test():
    import math
    s = math.cos(1)
s = math.cos(1)

是的,至少在上面的例子中,模块将是函数的本地模块(我使用的是 Python 3.6)。

示例:

Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
def test():
...     import math
...     s = math.cos(1)
...
g = math.cos(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined