Reputation: 9321
My class looks like this:
class A:
def __init__(self):
self.bar = []
...
@property
def foo(self):
return bar
Is there a way to find out inside foo
whether a method will be called on its return value? I would like to be able to change the return value of foo
depending on whether
a.foo.foobar()
or
a.foo
is called.
Upvotes: 1
Views: 59
Reputation: 78886
for the fun of it...
#!/usr/bin/python
import traceback
def how_was_i_called():
call=traceback.extract_stack(limit=2)[0][3]
print "I was called like this: %s"%call
how_was_i_called()
try:
how_was_i_called().foobar()
except AttributeError:
pass
returns:
I was called like this: how_was_i_called()
I was called like this: how_was_i_called().foobar()
but please do not use hacks like this in real applications...
Upvotes: 2
Reputation: 77902
You could use a proxy class wrapping self.bar
(or just self
FWIW) in foo()
) and overload the proxy's __getattr__()
or __getattribute__
methods (more tricky and can slow down your program quite a bit but well...).
Now the question is: what is your real problem ? There might be better / safer solutions...
Upvotes: 2
Reputation: 1121834
No, there is not. foo
returns, and what happens with the return value after that is an entirely separate issue.
You could do this, for example:
result = a.foo
if some_condition:
result.foobar()
e.g. accessing the foobar
method on a.foo
is an entirely separate expression that may or may not be executed. This could happen at a much later time too, or in a separate thread, or after serialising the object to disk, then loading it again, etc.
You can hook into attribute access on the returned object, but that'll be too late for your foo
property to alter behaviour.
Upvotes: 1