1

I'd like to know whether my method is called by the user directly or by another method. To make it less abstract:

class myclass():
    def __init__(self, ...):
        ....

    def method1(self, ...):
        ...
        --- some if statement --
        print "Hello"
        return something

    def callmethod(self, ...):
        x = self.method1(...)
        return x*2

 myinstance = myclass(...)
 myinstance.method1(...)
 --> 'Hello'
 myinstance.callmethod(...)
 --> - 

Hopefully my class makes clear what I'd like to do: When the user calls 'method1' the print statement shall be executed but if 'method1' is called by another method like 'callmethod' the print statement shall not be executed. Therefore I need 'some if statement' which checks whether 'method1' is called by the user directly or by another method. Thanks for you help!

John
  • 521
  • 2
  • 5
  • 12

2 Answers2

4

No, and you don't want to do this.

If you want to change behaviour depending on the way a method is called, then you need to use a parameter. You can use a default value to make this simpler, for example:

def method1(self, do_print=True):
    ...
    if do_print:
        print "Hello"
    return something

def callmethod(self, ...):
    x = self.method1(do_print=False)
    return x*2

Now, calling myinstance.method1() will print, whereas myinstance.callmethod() will not.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

It's actually achievable using the python inspector, like e.g.:

import inspect

class myclass():
    def __init__(self):
        pass

    def method1(self):
        (frame, filename, line_number, function_name, lines, index) = inspect.getouterframes(inspect.currentframe())[1]
        if function_name == '<module>':
            print "Hello"
        return 2

    def callmethod(self):
        x = self.method1()
        return x*2

myinstance = myclass()
myinstance.method1()
myinstance.callmethod()

but I agree with Daniel it's not an elegant way to achieve the result as it hides some behaviour.

For further details also see: this post

Community
  • 1
  • 1
guandalf
  • 366
  • 2
  • 6