0
# python3
def foo(a):
    class A:
        def say(self):
            print(a)
    return A
A = foo(1)
'__closure__' in dir(A.say) # True
a = A()
a.say.__closure__ # it returns the closure tuple
'__closure__' in dir(a.say) # False
'__closure__' in dir(a.say.__class__) # False
'__closure__' in dir(a.say.__class__.__class__) # False

In Python3, A.say is a function, and I know it has__closure__ attribute. __closure__ not in dir(a.say) or its super class, but a.say.__closure__ returns the closure tuple. It makes me confuse. Thanks.

dragonfly
  • 33
  • 5
  • possible duplicate http://stackoverflow.com/questions/14413946/what-exactly-is-contained-within-a-obj-closure – styvane Feb 05 '15 at 04:55
  • @Styvane thanks for your commit. They are not completely duplicate. The answer you provide tells how __closure works. I have edited my question to make it clear. – dragonfly Feb 05 '15 at 05:41

1 Answers1

1

I don't know in Python the internal implementation of objects with type instancemethod but I think it is how __getattr__ works in instance method objects.

My guess is when you say a.say.__closure__ it first looks up for __closure__ in dir(a.say) and then fallbacks on dir(a.say.im_func).

>>> a = foo(1)()
>>> print type(a.say)
>>> instancemethod

>>> a.say.im_func.__closure__
>>> (<cell at 0x10a00f980: int object at 0x7fef29e098b8>,)

>>> '__closure__' in dir(a.say.im_func)
>>> True
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • thanks @ozgurv . My question is not very clear, and I have edited it. The **__closure__** attribute is in dir(inner_function). **__closure__** attribute is not in dir(a.say), but a.say.__closure__ does return the closure tuple. It makes me confuse. In fact, **__closure__** is in dir(A.say), because A.say is a function in Python3. – dragonfly Feb 05 '15 at 05:46
  • thanks. You are right. The **im_func** attribute is the original function object, and it's the original function object that contains the **__closure__** attribute. – dragonfly Feb 05 '15 at 06:55