I always thought that Python 2.7 functions refer to the scope they were defined in. Consider the following code. Why is the second output not "calculating: sin"?
Is there any way to modify the code so it is working as expected?
import math mymath = dict() for fun in ["sin", "cos"]: def _impl(val): print "calculating: %s" % fun return getattr(math, fun)(val) mymath[fun] = _impl # calculating: cos print mymath["cos"](math.pi) # calculating: cos <- why? print mymath["sin"](math.pi)