1

I have 2 classes with a method called pick_up_phone.

class Work(object):

   def pick_up_phone(self):
       make_call()

class Home(object):

    def pick_up_phone(self):
       make_call()

The function make_call is not part of the class. How can I print the name of class that instigated the function within the function itself without passing anything to that function?

For example something like...

def make_call()
  print(????__.class__.__name__)???? <--- prints Home or Work class
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
MarkK
  • 968
  • 2
  • 14
  • 30
  • 1
    Odd requirements. Why wouldn't you either make it part of the super class, or pass in the instance as a parameter? – Daniel Roseman Aug 20 '15 at 10:20
  • It is odd, but the example explains the situation I have where I don't control the calling class only the function. I need to determine which class called my function. I know how to achieve this using ``self.__class__.__name__`` however, with a function this wouldn't work. – MarkK Aug 20 '15 at 10:23
  • 2
    possible duplicate of [How to use inspect to get the caller's info from callee in Python?](http://stackoverflow.com/questions/3711184/how-to-use-inspect-to-get-the-callers-info-from-callee-in-python) – Peter Wood Aug 20 '15 at 10:24
  • You can [access the stack frame using `inspect`](https://docs.python.org/2/library/inspect.html#the-interpreter-stack) – Peter Wood Aug 20 '15 at 10:25
  • @PeterWood I looked at that answer, but I don't understand how it relates very well. Maybe I just don't understand the answer given. – MarkK Aug 20 '15 at 10:26

2 Answers2

2

You could use the inspect module:

from inspect import getouterframes, currentframe


def make_call():
    print getouterframes(currentframe())[-1][-2][0]


class Work(object):
    def pick_up_phone(self):
        make_call()


class Home(object):
    def pick_up_phone(self):
        make_call()


Home().pick_up_phone()
Work().pick_up_phone()

Output:

Home().pick_up_phone()

Work().pick_up_phone()
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
0

You could get call stack from traceback module (see examples here Print current call stack from a method in Python code), but as Daniel said it is very bad approach in most cases.

Community
  • 1
  • 1
ISanych
  • 21,590
  • 4
  • 32
  • 52