Python: can a decorator determine if a function is being defined inside a class?

前端 未结 6 763
Happy的楠姐
Happy的楠姐 2021-02-07 11:58

I\'m writing a decorator, and for various annoying reasons[0] it would be expedient to check if the function it is wrapping is being defined stand-alone or as part of a class (a

6条回答
  •  无人及你
    2021-02-07 12:32

    A little late to the party here, but this has proven to be a reliable means of determining if a decorator is being used on a function defined in a class:

    frames = inspect.stack()
    
    className = None
    for frame in frames[1:]:
        if frame[3] == "":
            # At module level, go no further
            break
        elif '__module__' in frame[0].f_code.co_names:
            className = frame[0].f_code.co_name
            break
    

    The advantage of this method over the accepted answer is that it works with e.g. py2exe.

提交回复
热议问题