Defining Python decorators for a complete module

前端 未结 2 784
抹茶落季
抹茶落季 2020-12-09 18:06

I have a module which contains a lot of functions (more than 25). I want to add a common decorator function to each of these functions. The normal way to do is to add a @dec

2条回答
  •  伪装坚强ぢ
    2020-12-09 18:44

    If your decorator is called my_decorator

    ### Decorate all the above functions
    import types
    for k,v in globals().items():
        if isinstance(v, types.FunctionType):
            globals()[k] = my_decorator(v)
    

    You could also apply this to the module after importing it

    import othermodule
    import types
    for k,v in vars(othermodule).items():
        if isinstance(v, types.FunctionType):
            vars(othermodule)[k] = my_decorator(v)
    

提交回复
热议问题