Louis Ng
Louis Ng

Reputation: 553

Given a function with closure, can I refer back to it's closure scope?

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!

Upvotes: 0

Views: 46

Answers (1)

Woody1193
Woody1193

Reputation: 8000

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.

Upvotes: 2

Related Questions