0

I am editing some code that is being called by another system that I do not control. This system initializes my class from a few different places. I need to perform different things depending on where my class is called from. Is there a way I can find where my object is being initialized?

A.py:

class InitializerA:
    def calling_function(self):
        Called()

class InitializerB:
    def calling_function(self):
        Called()

B.py:

class Called:
    def __init__(self):
        # I want to know here whether it is being called by InitializerA or InitializerB
user1742188
  • 4,563
  • 8
  • 35
  • 60
  • Why do you want that? What's the context in which that would be useful? – jonrsharpe Aug 06 '18 at 09:45
  • Called can do different things depending on who is calling it. Unfortunately, this is some legacy code that needs to be modified, and I cannot add a new argument to the initializers. – user1742188 Aug 06 '18 at 09:48
  • That seems like a terrible design, what has led to that? How is it currently handled? – jonrsharpe Aug 06 '18 at 09:49
  • Agreed, this is not ideal. Initially, Called would do the same thing for all the Initializers, but due to a change in business requirements, it now needs to do different things. – user1742188 Aug 06 '18 at 09:50
  • You'd probably be better off making specific subclasses of called for each initializer if that would be possible – jc1850 Aug 06 '18 at 09:54
  • 2
    Your requirements don't make much sense to me. If you're refactoring to add new functionality, why the limits on what you can change to get there? Please [edit] the question to provide more useful context, this seems like an XY problem. – jonrsharpe Aug 06 '18 at 09:59
  • I've added some context. The calling code is a different system that I cannot modify. – user1742188 Aug 06 '18 at 10:09

2 Answers2

1

I was able to find the answer by modifying the method given in this question: How to get the caller class name inside a function of another class in python?

The inspect library helped me inspect the call stack.

user1742188
  • 4,563
  • 8
  • 35
  • 60
0

You could pass the class initializing it as an parameter to Called i.e:

class class InitializerA:
def calling_function(self):
    Called(self.__name__)


class Called:
def __init__(self, initializer):
     self.initializer = initializer
jc1850
  • 1,101
  • 7
  • 16
  • Unfortunately, this is some legacy code that needs to be modified, and I cannot add a new argument to the initializers. – user1742188 Aug 06 '18 at 09:49