0

I have a case, let's say:

class A:
    def store():
        name = 'unknown'
        for name in inspect.stack():
            if 'method_a' in name:
                print('Called x times from method A')
            if 'method_b' in name:
                print('Called x times from method B')

class B:
    def __init__():
        self.a = A()

    def method_a():
        self.a.store()
        self.a.store()

    def method_b():
        self.a.store()
        self.a.store()
        self.a.store()

So, I'm interested to know how many times has the store method been called from methodA and from methodB from class B. I can't modify class B, the logic should be implemented only from store method of class A.

Does the inspect library offer such a feature? Or, I can extract the result I want in some other way?

gentiand
  • 31
  • 3
  • This [thread](https://stackoverflow.com/questions/1301735/counting-python-method-calls-within-another-method) should give you a head start on how to build this. – metatoaster Mar 16 '21 at 09:33
  • Thank you for your answer! I need the exact functionality as this one: https://stackoverflow.com/a/1301926/11727882 But, in my case I have to add `@counted(store)` to the `method_a` and `method_b`. Is there a way to achieve the desired functionality without touching class `B`? – gentiand Mar 16 '21 at 10:25
  • Yes, but you have to take the ideas presented there (read the other answers too) and build it. – metatoaster Mar 16 '21 at 11:35

0 Answers0