How to use the decorator.FunctionMaker function in decorator

To help you get started, we’ve selected a few decorator examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github smarie / python-pytest-steps / pytest_steps / decorator_hack.py View on Github external
from inspect import signature
except ImportError:
    from funcsigs import signature

try:
    from decorator import iscoroutinefunction
except ImportError:
    try:
        from inspect import iscoroutinefunction
    except ImportError:
        # let's assume there are no coroutine functions in old Python
        def iscoroutinefunction(f):
            return False


class MyFunctionMaker(FunctionMaker):
    """
    Overrides FunctionMaker so that additional arguments can be inserted in the resulting signature.
    """

    def refresh_signature(self):
        """Update self.signature and self.shortsignature based on self.args,
        self.varargs, self.varkw"""
        allargs = list(self.args)
        allshortargs = list(self.args)
        if self.varargs:
            allargs.append('*' + self.varargs)
            allshortargs.append('*' + self.varargs)
        elif self.kwonlyargs:
            allargs.append('*')  # single star syntax
        for a in self.kwonlyargs:
            allargs.append('%s=None' % a)
github smarie / python-pytest-cases / pytest_cases / decorator_hack.py View on Github external
from inspect import signature
except ImportError:
    from funcsigs import signature

try:
    from decorator import iscoroutinefunction
except ImportError:
    try:
        from inspect import iscoroutinefunction
    except ImportError:
        # let's assume there are no coroutine functions in old Python
        def iscoroutinefunction(f):
            return False


class MyFunctionMaker(FunctionMaker):
    """
    Overrides FunctionMaker so that additional arguments can be inserted in the resulting signature.
    """

    def refresh_signature(self):
        """Update self.signature and self.shortsignature based on self.args,
        self.varargs, self.varkw"""
        allargs = list(self.args)
        allshortargs = list(self.args)
        if self.varargs:
            allargs.append('*' + self.varargs)
            allshortargs.append('*' + self.varargs)
        elif self.kwonlyargs:
            allargs.append('*')  # single star syntax
        for a in self.kwonlyargs:
            allargs.append('%s=None' % a)
github qiime2 / qiime2 / qiime2 / core / util.py View on Github external
# Descriptor protocol for creating an attribute that is bound to an
# (arbitrarily nested) attribute accessible to the instance at runtime.
class LateBindingAttribute:
    def __init__(self, attribute):
        self._attribute = attribute

    def __get__(self, obj, cls=None):
        attrs = self._attribute.split('.')
        curr_attr = obj
        for attr in attrs:
            curr_attr = getattr(curr_attr, attr)
        return staticmethod(curr_attr).__get__(obj, cls)


# Removes the first parameter from a callable's signature.
class DropFirstParameter(decorator.FunctionMaker):
    @classmethod
    def from_function(cls, function):
        return cls.create(function, "return None", {})

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.signature = self._remove_first_arg(self.signature)
        self.shortsignature = self._remove_first_arg(self.shortsignature)

    def _remove_first_arg(self, string):
        return ",".join(string.split(',')[1:])[1:]


def _immutable_error(obj, *args):
    raise TypeError('%s is immutable.' % obj.__class__.__name__)
github qiime2 / qiime2 / qiime / sdk / visualizer.py View on Github external
import qiime.sdk
import qiime.core.type as qtype
from qiime.core.path import TempPath


# Descriptor protocol for methods with dynamic signatures built from the
# callables they wrap.
class DispatchableSignature:
    def __init__(self, method):
        self._method = method

    def __get__(self, obj, cls=None):
        return staticmethod(getattr(obj, self._method)).__get__(obj, cls)


class DropFirstParameter(decorator.FunctionMaker):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.signature = self._remove_first_arg(self.signature)
        self.shortsignature = self._remove_first_arg(self.shortsignature)

    def _remove_first_arg(self, string):
        return ",".join(string.split(',')[1:])[1:]

    @classmethod
    def from_function(cls, function):
        return cls.create(function, "return None", {})


# TODO a ton of code is shared between Method and Visualizer, refactor!
class Visualizer:
    __call__ = DispatchableSignature('_dynamic_call')
github otsaloma / gaupol / aeidon / deco.py View on Github external
def decorator_apply(dec, fun):
    """Rewrap `dec` to preserve function signature."""
    import decorator
    return decorator.FunctionMaker.create(
        fun, "return decorated(%(signature)s)",
        dict(decorated=dec(fun)), __wrapped__=fun)
github librosa / librosa / librosa / cache.py View on Github external
def decorator_apply(dec, func):
                """Decorate a function by preserving the signature even if dec
                is not a signature-preserving decorator.

                This recipe is derived from
                http://micheles.googlecode.com/hg/decorator/documentation.html#id14
                """

                return FunctionMaker.create(
                    func, 'return decorated(%(signature)s)',
                    dict(decorated=dec(func)), __wrapped__=func)
github spraakbanken / sparv-pipeline / python / sb / util / membrane.py View on Github external
def add_extra_methods(orig_fun):
        """
        Stores __load_argument, __set_extendable, and load in the
        function object. Uses decorator.FunctionMaker to give
        the returned function the same signature as the original.
        """
        obj = MembraneDecorator(orig_fun)
        res = decorator.FunctionMaker.create(
            orig_fun, 'return decorated(%(signature)s)',
            dict(decorated=obj), __wrapped__=orig_fun,
            __load_argument = obj.load_argument,
            __set_extendable = obj.set_extendable,
            load = obj.get_loaded_argument)
        return res
github CellProfiler / CellProfiler / decorator.py View on Github external
def decorator(caller, func=None):
    """
    decorator(caller) converts a caller function into a decorator;
    decorator(caller, func) decorates a function using a caller.
    """
    if func is None: # returns a decorator
        fun = FunctionMaker(caller)
        first_arg = inspect.getargspec(caller)[0][0]
        src = 'def %s(%s): return _call_(caller, %s)' % (
            caller.__name__, first_arg, first_arg)
        return fun.make(src, dict(caller=caller, _call_=decorator),
                        undecorated=caller)
    else: # returns a decorated function
        fun = FunctionMaker(func)
        src = """def %(name)s(%(signature)s):
    return _call_(_func_, %(signature)s)"""
        return fun.make(src, dict(_func_=func, _call_=caller), undecorated=func)
github CellProfiler / CellProfiler / decorator.py View on Github external
def decorator(caller, func=None):
    """
    decorator(caller) converts a caller function into a decorator;
    decorator(caller, func) decorates a function using a caller.
    """
    if func is None: # returns a decorator
        fun = FunctionMaker(caller)
        first_arg = inspect.getargspec(caller)[0][0]
        src = 'def %s(%s): return _call_(caller, %s)' % (
            caller.__name__, first_arg, first_arg)
        return fun.make(src, dict(caller=caller, _call_=decorator),
                        undecorated=caller)
    else: # returns a decorated function
        fun = FunctionMaker(func)
        src = """def %(name)s(%(signature)s):
    return _call_(_func_, %(signature)s)"""
        return fun.make(src, dict(_func_=func, _call_=caller), undecorated=func)
github dsacre / mididings / mididings / arguments.py View on Github external
assert ((len(self.constraints) == len(self.arg_names)
                    and not self.have_varargs)
             or (len(self.constraints) == len(self.arg_names) + 1
                    and self.have_varargs))

        if self.add_varargs:
            # add varargs to the signature and use decorator.FunctionMaker
            # directly to create the decorated function
            orig_signature = inspect.getargspec(f)
            assert orig_signature.varargs is None
            signature = orig_signature._replace(varargs='args')
            evaldict = self.wrapper.__globals__.copy()
            evaldict['_call_'] = self.wrapper
            evaldict['_func_'] = f
            return decorator.FunctionMaker.create(
                '%s%s' % (f.__name__, inspect.formatargspec(*signature)),
                'return _call_(_func_, %(shortsignature)s)',
                evaldict, undecorated=f, __wrapped__=f, doc=f.__doc__)
        else:
            return decorator.decorator(self.wrapper, f)