GrahamDumpleton / wrapt

A Python module for decorators, wrappers and monkey patching.
BSD 2-Clause "Simplified" License
2.03k stars 231 forks source link

patch_function_wrapper does not accept "enabled" argument #234

Open MrFizzyBubbs opened 1 year ago

MrFizzyBubbs commented 1 year ago

I would like to use patch_function_wrapper to patch a method of a third part module with the enabled argument as described here in https://wrapt.readthedocs.io/en/latest/decorators.html#dynamically-disabling-decorators. However, this does not seem to be supported out of the box. I was able to easily write my own (see below) but was curious if there was a reason wrapt doesn't support this out of the box or if there is a simpler approach I'm missing.

def patch_function_wrapper_with_enabled(module, name, enabled=None):
    def _wrapper(wrapper):
        return wrapt.wrap_object(
            module, name, wrapt.FunctionWrapper, (wrapper,), {"enabled": enabled}
        )

    return _wrapper
GrahamDumpleton commented 1 year ago

Are you using a callable for enabled or a literal boolean?

MrFizzyBubbs commented 1 year ago

I am using a callable for enabled.

GrahamDumpleton commented 1 year ago

Yeah, for that use case it would indeed be helpful. The enabled argument being able to be a callable was only added sometime after the patching functions were created and likely didn't think about revising the patch functions due to that change. I'll try and set aside some time to work out the places it needs to change and whether there are other functions that could pass it through besides just that singe patch function.

MrFizzyBubbs commented 1 year ago

Very cool, thank you!

MrFizzyBubbs commented 1 year ago

Hello! I was curious if you were still planning on implementing this change.

GrahamDumpleton commented 1 year ago

Have just overlooked it, been very busy with work over the last few months. Also just back from a trip. As I recover and work out where I am up to with things will try and look at it.

GrahamDumpleton commented 1 year ago

I have added the enabled argument to @patch_function_wrapper() decorator in develop branch of Git repo for 1.16.0.