The Python compiler optimizes access to local variables by recognizing at compile time whether the calls that the function executes are local (i.e., names assigned or otherwise associated with the function). Therefore, if you code:
def lv1(d): locals().update(d) print zap
the compiler “knows” that barename zap NOT local (not assigned in the lv1 function), and therefore it compiles the code to access it as global, and not that d does not matter.
If you prefer slow and bloated code, you can defeat optimization by using exec inside the function - when the compiler sees the exec keyword, it KNOWS that you are trying to make your code as slow, bloated and buggy as possible, and therefore it works, doesn't optimizing in any way, roughly.
So, the following code works as you wish:
def lv1(d): exec "" locals().update(d) print zap lv1({'zap': 23})
it emits 23 as you want.
I hope that from the above "calm humor" I realized that the technique is not recommended, but I would have better formulated it very explicitly: for dubious syntactic pleasure to write print zap instead of print locals()['zap'] , you They pay a healthy price with performance point of view. Nevertheless, like all kinds of dangerous tools that can be useful in rare cases for really experienced programmers at the guru level, who really really know what they are doing and why, exec is available for you, use it) at your whim: Python NOT standing in your way! -)
Alex martelli
source share