简体   繁体   中英

Importing a module after a function is defined

How does the following work in python:

def f(num):
    time.sleep(num)
    return num

>>> f(2)
NameError: name 'time' is not defined
>>> import time
>>> f(2)
2

How does python "insert" the module into that function, or how does the lookup mechanism work there as to be able to import something after the function is created?

Unlike a compiler, which statically binds names to fixed addresses at compilation time, Python code is executed by an interpreter that resolves names at runtime, so what the name time refers to is not resolved by the interpreter until the execution runs into an expression that actually references it, at which point the interpreter will follow the name resolution rules to resolve the name into an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM