Python 为什么可以';我不能在函数中使用'import*'?
这是意料之中的事Python 为什么可以';我不能在函数中使用'import*'?,python,python-2.x,Python,Python 2.x,这是意料之中的事 def outer_func(): from time import * print time() outer_func() 我可以在上下文中定义嵌套函数,并从其他嵌套函数调用它们: def outer_func(): def time(): return '123456' def inner_func(): print time() inner_func() outer_func() def
def outer_func():
from time import *
print time()
outer_func()
我可以在上下文中定义嵌套函数,并从其他嵌套函数调用它们:
def outer_func():
def time():
return '123456'
def inner_func():
print time()
inner_func()
outer_func()
def outer_func():
from time import time
def inner_func():
print time()
inner_func()
outer_func()
我甚至可以导入单个函数:
def outer_func():
def time():
return '123456'
def inner_func():
print time()
inner_func()
outer_func()
def outer_func():
from time import time
def inner_func():
print time()
inner_func()
outer_func()
但是,在函数“outer_func”中不允许抛出SyntaxError:import*,因为它包含一个带有自由变量的嵌套函数
:
def outer_func():
from time import *
def inner_func():
print time()
inner_func()
outer_func()
我知道这不是最佳实践,但为什么不起作用?编译器无法知道时间模块是否导出名为
time
的对象
嵌套函数的自由变量在编译时绑定到闭包单元。闭包单元格本身指向编译代码中定义的(局部)变量,而不是全局变量,全局变量根本不绑定。看,;函数通过func\u globals
属性引用其全局,而func\u closure
属性包含一系列闭包单元格(或None
)
因此,不能在嵌套范围中使用动态导入语句
为什么嵌套函数需要闭包单元格呢?因为在函数本身完成时,需要一种引用局部函数变量的机制:
def foo(spam):
def bar():
return spam
return bar
afunc = foo('eggs')
通过调用
foo()。因此,这些单元格以及它们所受的限制。有趣的问题…“这是预期的结果”-在哪个python版本中?@thg435 python 2。Python3更为严格,它拒绝了第一个示例,只允许在模块级使用SyntaxError:import*
。我添加了python-2.x标记以澄清问题。@WilfredHughes:python 2.6和2.7也拒绝运行该标记。@thg435适用于python 2.7,但有一个警告nested2.py:1:SyntaxWarning:import*仅允许在模块级别\n def outer_func():\n1353343092.54