def f():
from math import *
return cos(3.0)
https://peps.python.org/pep-0227/#import-used-in-function-sc... notes "The language reference specifies that import * may only occur in a module scope. (Sec. 6.11) The implementation of C Python has supported import * at the function scope."Python 2.1 added static nested scopes (see the PEP 227 link), which enabled a much faster locals lookup. With that one case excluded, all of the locals can be determined at parse/byte-compile time, stored in a simple vector, and referenced by offset:
>>> z = 0
>>> def f(x):
... y = x + z
... return y * 2
...
>>> import dis
>>> dis.dis(f)
1 0 RESUME 0
2 2 LOAD_FAST 0 (x)
4 LOAD_GLOBAL 0 (z)
14 BINARY_OP 0 (+)
18 STORE_FAST 1 (y)
3 20 LOAD_FAST 1 (y)
22 LOAD_CONST 1 (2)
24 BINARY_OP 5 (*)
28 RETURN_VALUE
The "LOAD_FAST" uses offset 0 to store "x" and offset 1 to store "y", while "z" required a LOAD_GLOBAL to find z in the globals() dictionary.