I need to count the number of times recursion in a python program. So basically I need a static variable kind of thing (like in C) which can count the number of times the function is called.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- PHP Recursively File Folder Scan Sorted by Modific
- Evil ctypes hack in python
Just pass a counter with the recursion
Or im sure there is some fancy decorator, Im gonna investigate that now...
Another method using
global
:One way would be to use a
list
containing one element that keeps a count of how many times the function was entered.You can define a Counter callable class with which you can wrap any function:
The advantage here being that you can use it for any function, without having to modify it's signature.
EDIT: Thanks to @Tom Zych for spotting a bug. The
recur
name has to be masked by the callable class instance for this to work. More info on decorators here:http://wiki.python.org/moin/PythonDecoratorLibrary#Counting_function_calls