Counting python method calls within another method

后端 未结 3 1623
囚心锁ツ
囚心锁ツ 2020-11-29 10:11

I\'m actually trying doing this in Java, but I\'m in the process of teaching myself python and it made me wonder if there was an easy/clever way to do this with wrappers or

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 11:08

    Sounds like almost the textbook example for decorators!

    def counted(fn):
        def wrapper(*args, **kwargs):
            wrapper.called += 1
            return fn(*args, **kwargs)
        wrapper.called = 0
        wrapper.__name__ = fn.__name__
        return wrapper
    
    @counted
    def foo():
        return
    
    >>> foo()
    >>> foo.called
    1
    

    You could even use another decorator to automate the recording of how many times a function is called inside another function:

    def counting(other):
        def decorator(fn):
            def wrapper(*args, **kwargs):
                other.called = 0
                try:
                    return fn(*args, **kwargs)
                finally:
                    print '%s was called %i times' % (other.__name__, other.called)
            wrapper.__name__ = fn.__name__
            return wrapper
        return decorator
    
    @counting(foo)
    def bar():
        foo()
        foo()
    
    >>> bar()
    foo was called 2 times
    

    If foo or bar can end up calling themselves, though, you'd need a more complicated solution involving stacks to cope with the recursion. Then you're heading towards a full-on profiler...

    Possibly this wrapped decorator stuff, which tends to be used for magic, isn't the ideal place to be looking if you're still ‘teaching yourself Python’!

提交回复
热议问题