1

Trying to use How to get the caller class name inside a function of another class in python? I ran into a peculiar issue with decorated methods.

stack[1].frame.f_locals["self"].__class__.__name__ works in case of instance method call but when applying over class methods (function with @staticmethod decorator) it throws an error:

src = '<{}>.'.format(stack[1].frame.f_locals["self"].__class__.__name__)
KeyError: 'self'

The code is given below (working for instance method with self param but nor for @staticmethod decorated class methods):

def some_func():
    '... some_code ...'
    import inspect
    stack = [x for x in inspect.stack() if 'My_Module' in str(x)]
    try:
        src = '<{}>.'.format(stack[1].frame.f_locals["self"].__class__.__name__)
    except:
        from traceback import format_exc
        print(format_exc())
        src = ''
   '... some_code ...'

class SomeClass:
    @staticmethod
    def tester():
        some_func()

Any clues?

Ulysses
  • 5,616
  • 7
  • 48
  • 84
  • I thinks it depends on how your caller class, for example, `def run(self):` should be works but `def eval_bob(cls):` does not. In this case, your `some_func` does not declare `self`. – cmj Aug 19 '22 at 09:12
  • Sorry - my fault - i wanted to inspect a static method - corrected the question – Ulysses Aug 19 '22 at 09:34
  • What if you have `class Foo: ...; def bar(): some_func(); Foo.foo = bar; Foo.foo()`? What do you want as a result in this case? – a_guest Aug 19 '22 at 12:20

0 Answers0