when working with python, it bothered me that while obj.method() is perfectly fine, method(obj) isn't allowed. So I figured I'd try to write some code to fix that. I came up with the next:
def globalclassfuncs(defobj):
for i in inspect.getmembers(defobj, predicate=inspect.ismethod):
def scope():
var = i[0];
setattr(sys.modules[__name__], i[0], lambda obj, *args: getattr(obj, var)(*args));
scope();
However, there's something weird with this. When I remove def scope():
and scope()
, so that it'll run without a function definition in the for loop, or when I change the getattr()
function to use i[0]
directly instead of through var
, somehow all new defined functions point to the last defined function instead of the function they should point to. Why does this behaviour change so much on such small changes in the code?
Seems like a case of late binding closure