Why can't I use `import *` in a function?

后端 未结 1 903
予麋鹿
予麋鹿 2021-02-19 03:52

This works as expected

def outer_func():
    from time import *

    print time()

outer_func()

I can define nested functions in the context fi

1条回答
  •  北恋
    北恋 (楼主)
    2021-02-19 04:46

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

    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')
    

    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.

    0 讨论(0)
提交回复
热议问题