In a function, how to get the caller object ?

P

popov

Look at this code:

class C:
def func():
<caller_of_func>.my_attrib = 1
func = staticmethod(func)

C.func()

c = C()
c.func()

In func, I would like to get C for the first call, and c for the
second one, to be able to add a new attribute to this object (so that
would add the attribute either to the class object or to the
instance). How can I do this ?
I tried to give a look to the inspect module with no luck.
 
B

Bengt Richter

Look at this code:

class C:
def func():
<caller_of_func>.my_attrib = 1
func = staticmethod(func)

C.func()

c = C()
c.func()

In func, I would like to get C for the first call, and c for the
second one, to be able to add a new attribute to this object (so that
would add the attribute either to the class object or to the
instance). How can I do this ?
I tried to give a look to the inspect module with no luck.

You need something other than staticmethod, that delivers an ordinary method or
an effective classmethod depending on access via the class or an instance, e.g.,
(not tested beyond what you see):
(BTW, I added a value parameter to your func, for less ambiguous example results)
... def __get__(self, obj, cls):
... if obj is None: return self.fun.__get__(cls, cls)
... else: return self.fun.__get__(obj, type(obj))
... def __init__(self, fun):
... self.fun = fun
... ... def func(caller_of_func, value=1):
... caller_of_func.my_attrib = value
... func = SpecialMethod(func)
... ['__dict__', '__module__', '__weakref__', '__doc__', 'func']

The above shows not my_attrib
['__module__', 'my_attrib', 'func', '__dict__', '__weakref__', '__doc__']

But after C.func() it is there
1

now we make an instance
<bound method C.func of <__main__.C object at 0x00904070>>

looks like an ordinary bound method (though defined with "caller_of_func" in place of "self").
1

The instance attribute shadows the class attribute, so we can uncover the latter
by deleting the former:
1

That's really C.my_attrib found through standard attribute search.

To get more info, read about descriptors.

Regards,
Bengt Richter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top