0

I would like to refer to a function's closure scope:

class C():
    def d(self):
        def fn_class():
            return
        return fn_class

fn = C().d()
fn
# <function C.d.<locals>.fn_class at 0x0000025E8A381E18>
fn.__closure__
# None

All I want to do is that, given only fn, I want to reference back to self, fn.__closure__ doesn't seem to work, I need some help, thanks!

Louis Ng
  • 533
  • 1
  • 7
  • 16

1 Answers1

2

What you're doing is correct but because fn_class doesn't pull in any information from d or C, __closure__ has no information to give you so it is None.

Now, if you were to modify d like this:

def d(self):
    x = 5
    def fn_class():
        return x
    return fn_class

And then do:

fn = C().d()
fn
# <function C.d.<locals>.fn_class at 0x0000025E8A381E18>
fn.__closure__
# (<cell at 0x7fedb0a5be88: int object at 0x9a3180>,)

For more information, see this question.

Now, with regard to your question, I don't think using __closure__ will work because self isn't defined in a parent function - in this case, d - but is passed in from the outside. If you were to modify d so that you passed self in, like this:

def d(self):
    def fn_class(self):
        return
    return fn_class

Then, you could do:

fn.__code__.co_varnames
# ('self',)

but getting back to the actual location of self in that instance would be much more difficult.

Woody1193
  • 7,252
  • 5
  • 40
  • 90
  • Oh, I can totally see the problem, I am framework developer, function `fn_class` is written by other developers and the `fn_class` is passes to my framework, so I have no control over the content of `fn_class`. I need a more hacky way to do it. – Louis Ng Feb 10 '20 at 03:35
  • If `fn_class` doesn't close over anything then it isn't a closure in the first place. [What problem are you actually trying to solve?](http://xyproblem.info/) – kaya3 Feb 10 '20 at 03:38
  • Thanks for helping guys, I think I will enforce everyone to pass me the self also instead of doing anything hacky! Now everyone gotta change their codes. – Louis Ng Feb 10 '20 at 04:00