Let's say I have a Python function f
and fhelp
. fhelp
is designed to call itself recursively. f
should not be called recursively. Is there a way for f
to determine if it has been called recursively?
相关问题
- 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
Use the traceback module for this:
So, if any entry in the stack indicates that the code was called from
f
, the call was (in)directly recursive. Thetraceback.extract_stack
method gives you an easy access to this data. Theif len(l[2] ...
statement in the example below simply counts the number of exact matches of the name of the function. To make it even prettier (thanks to agf for the idea), you could make it into a decorator:You could use a flag set by a decorator:
Then you can do
and if
f
gets called again while it's running,called
will beTrue
and it will raise an exeption.