如果我在函数中导入模块,变量是否是本地的?

时间:2017-02-17 01:57:57

标签: python python-3.x scope python-import

如果我在函数(本地范围)内部导入python 3中的模块,导入的东西是否会在函数本地?

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

1 个答案:

答案 0 :(得分:0)

是的,该模块将是函数的本地模块,至少在上面的示例中(我使用的是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