Given the following:
class MyClass:
def __init__(self, someval):
self.someval = someval
def get_a_function(self):
def result():
return self.someval
return result
inst = MyClass("my value")
func = inst.get_a_function()
I have only func, and would like to get inst. Is that possible, and if so, how? Note: I do not control MyClass or how inst is declared.
P.S. I know this is baaadddd style, but am curious if it can be done.
You notice how result returns
self.someval, meaning that it has a closure. All you need to do is to dive into that closure. To do that, use thefunc_closureattribute:Note that I am just accessing the first element of the closure. If the function is more complicated, it may have multiple objects in its closure, and you need to test for which one you want.
Edit: This is really bad style btw 🙂