2

I've a class calling another class's function, like this:

self.pool.get('some_value')

How do I get the caller class inside the get function ?

thanks before,

Edxz
  • 823
  • 2
  • 8
  • 22
  • Do you want the caller class or the caller object? Why do you need this? And why can't you pass it in as a parameter to the called function (callee)? – batbrat Mar 25 '14 at 08:52
  • You mean the caller object reference, right? Or do you mean the actual class name that was used to instantiate the caller object? – bosnjak Mar 25 '14 at 08:52
  • Anyway, this could be what you want: http://stackoverflow.com/questions/17065086/how-to-get-the-caller-class-name-inside-a-function-of-another-class-in-python – bosnjak Mar 25 '14 at 08:53
  • @batbrat: I can't, the function is being used alot, it's impossible to add another parameter to the function – Edxz Mar 25 '14 at 08:54
  • @Lawrence: I want to get the object reference, is this possible? thanks – Edxz Mar 25 '14 at 08:55

1 Answers1

6

You can do this via inspect. The contents of the get() function can be:

import inspect
myCaller = inspect.currentframe().f_back.f_locals['self']

After that, you have the caller's instance refered to by myCaller.

Disclaimer: this is not a good practice, because it ruins the whole point of encapsulation.

bosnjak
  • 8,424
  • 2
  • 21
  • 47
  • 1
    great answer, especially the disclaimer. Is it possible for this approach to fail/break under any circumstances that you know of? It looks standard, so I suppose it shouldn't. – batbrat Mar 25 '14 at 12:06
  • 1
    Thanks. I do not know of such circumstances, but then again, I avoid these kind of solutions so I haven't exactly tested it extensively. – bosnjak Mar 25 '14 at 12:19
  • Thx @Lawrence, I've finally found the class that I want using inspect, but it seems to be a performance hog, but I'll still use it. please tell me if u've a better solution, thanks :) – Edxz Mar 25 '14 at 12:56
  • I guess it should typically be avoided in code / projects that are not internals-laden by nature – matanster Oct 11 '20 at 15:24