为什么我不能在函数中使用 `import *`? [英] Why can't I use `import *` in a function?

查看:52
本文介绍了为什么我不能在函数中使用 `import *`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这按预期工作

def outer_func():
    from time import *

    print time()

outer_func()

我可以在上下文中定义嵌套函数并从其他嵌套函数调用它们:

I can define nested functions in the context fine and call them from other nested functions:

def outer_func():
    def time():
        return '123456'

    def inner_func():
        print time()

    inner_func()

outer_func()

我什至可以导入单个函数:

I can even import individual functions:

def outer_func():
    from time import time

    def inner_func():
        print time()

    inner_func()

outer_func()

然而,这会抛出 SyntaxError: import * is not allowed in function 'outer_func' 因为它包含一个带有自由变量的嵌套函数:

def outer_func():
    from time import *

    def inner_func():
        print time()

    inner_func()

outer_func()

我知道这不是最佳做法,但为什么不起作用?

I'm aware this isn't best practice, but why doesn't it work?

推荐答案

编译器无法知道 time 模块是否导出名为 time 的对象.

The compiler has no way of knowing whether the time module exports objects named time.

嵌套函数的自由变量在编译时绑定到闭包单元.闭包单元本身指向编译代码中定义的(局部)变量,而不是全局变量,全局变量根本没有绑定.请参阅 python 数据模型;函数通过 func_globals 属性引用它们的全局变量,func_closure 属性保存了一系列闭包单元(或 None).

The free variables of nested functions are tied to closure cells at compile time. Closure cells themselves point to (local) variables defined in compiled code, as opposed to globals, which are not tied at all. See the python data model; functions refer to their globals via the func_globals attribute, and the func_closure attribute holds a sequence of closure cells (or None).

因此,您不能在嵌套范围内使用动态导入语句.

As such, you cannot use a dynamic import statement in a nested scope.

为什么嵌套函数需要闭包单元?因为你需要一种机制来在函数本身完成后引用局部函数变量:

And why do nested functions need closure cells at all? Because you need a mechanism to refer to local function variables when the function itself has finished:

def foo(spam):
    def bar():
        return spam
    return bar

afunc = foo('eggs')

通过调用 foo() 我获得了一个引用范围变量的嵌套函数,编译器需要为解释器创建必要的引用,以便能够再次检索该范围变量.因此,细胞,以及对它们的限制.

By calling foo() I obtained a nested function that refers to a scoped variable, and the compiler needs to create the necessary references for the interpreter to be able to retrieve that scoped variable again. Hence the cells, and the limitations placed on them.

这篇关于为什么我不能在函数中使用 `import *`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆