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

前端 未结 6 839
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:45

    You could check if the decorator itself is being called at the module level or nested within something else.

    defined_in_class = inspect.currentframe().f_back.f_code.co_name != ""
    

提交回复
热议问题