5

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?

1 Answers1

6

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.

blhsing
  • 91,368
  • 6
  • 71
  • 106