简体   繁体   中英

Find a way to determine inside function if method is called on the return value?

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.

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...

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...

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()

eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM