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
5
  • 1
    Odd requirements. Why wouldn't you either make it part of the super class, or pass in the instance as a parameter? Commented Aug 20, 2015 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. Commented Aug 20, 2015 at 10:23
  • 2
    possible duplicate of How to use inspect to get the caller's info from callee in Python? Commented Aug 20, 2015 at 10:24
  • You can access the stack frame using inspect Commented Aug 20, 2015 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. Commented Aug 20, 2015 at 10:26

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.