Can a Python method check if it has been called from within itself?

前端 未结 2 951
旧时难觅i
旧时难觅i 2020-12-05 20:28

Let\'s say I have a Python function f and fhelp. fhelp is designed to call itself recursively. f should not be called rec

2条回答
  •  爱一瞬间的悲伤
    2020-12-05 20:59

    You could use a flag set by a decorator:

    def norecurse(func):
        func.called = False
        def f(*args, **kwargs):
            if func.called:
                print "Recursion!"
                # func.called = False # if you are going to continue execution
                raise Exception
            func.called = True
            result = func(*args, **kwargs)
            func.called = False
            return result
        return f
    

    Then you can do

    @norecurse
    def f(some, arg, s):
        do_stuff()
    

    and if f gets called again while it's running, called will be True and it will raise an exeption.

提交回复
热议问题