decopatch Library

1.4.10 · active · verified Sun Apr 12

decopatch is a Python library designed to simplify the creation of decorators. It addresses the common challenge in Python where writing decorators requires explicit handling of both with-parenthesis and without-parenthesis usages. The library is currently at version 1.4.10 and receives regular minor updates, maintaining an active development status.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the `function_decorator` to create a decorator that seamlessly works with and without parentheses, as well as with explicit arguments. The decorator `add_tag` adds a `tag` attribute to the decorated function.

from decopatch import function_decorator

@function_decorator
def add_tag(tag='hi!'):
    """
    Example decorator to add a 'tag' attribute to a function.
    :param tag: the 'tag' value to set on the decorated function.
    """
    def _apply_decorator(f):
        """
        This method is called when `@add_tag` is used on a function `f`.
        It should return a replacement for `f`.
        """
        setattr(f, 'tag', tag)
        return f
    return _apply_decorator

# Usage without parenthesis
@add_tag
def foo1():
    pass
assert foo1.tag == 'hi!'

# Usage with empty parenthesis
@add_tag()
def foo2():
    pass
assert foo2.tag == 'hi!'

# Usage with arguments
@add_tag('hello')
def foo3():
    pass
assert foo3.tag == 'hello'

print(f"foo1 tag: {foo1.tag}")
print(f"foo2 tag: {foo2.tag}")
print(f"foo3 tag: {foo3.tag}")

view raw JSON →