Python functools.update_wrapper() Examples

The following are 30 code examples of functools.update_wrapper(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module functools , or try the search function .
Example #1
Source File: formparser.py    From recruit with Apache License 2.0 6 votes vote down vote up
def exhaust_stream(f):
    """Helper decorator for methods that exhausts the stream on return."""

    def wrapper(self, stream, *args, **kwargs):
        try:
            return f(self, stream, *args, **kwargs)
        finally:
            exhaust = getattr(stream, "exhaust", None)
            if exhaust is not None:
                exhaust()
            else:
                while 1:
                    chunk = stream.read(1024 * 64)
                    if not chunk:
                        break

    return update_wrapper(wrapper, f) 
Example #2
Source File: help.py    From discord.py with MIT License 6 votes vote down vote up
def _inject_into_cog(self, cog):
        # Warning: hacky

        # Make the cog think that get_commands returns this command
        # as well if we inject it without modifying __cog_commands__
        # since that's used for the injection and ejection of cogs.
        def wrapped_get_commands(*, _original=cog.get_commands):
            ret = _original()
            ret.append(self)
            return ret

        # Ditto here
        def wrapped_walk_commands(*, _original=cog.walk_commands):
            yield from _original()
            yield self

        functools.update_wrapper(wrapped_get_commands, cog.get_commands)
        functools.update_wrapper(wrapped_walk_commands, cog.walk_commands)
        cog.get_commands = wrapped_get_commands
        cog.walk_commands = wrapped_walk_commands
        self.cog = cog 
Example #3
Source File: networking.py    From dephell with MIT License 6 votes vote down vote up
def aiohttp_repeat(func=None, *, count: int = 4):
    if func is None:
        return partial(func, count=count)

    async def wrapper(*args: Any, **kwargs: Any) -> Optional[Any]:
        for pause in range(1, count + 1):
            try:
                return await func(*args, **kwargs)
            except ClientError:
                if pause == count:
                    raise
                logger.debug('aiohttp payload error, repeating...', exc_info=True)
                sleep(pause)
        raise RuntimeError('unreachable')

    wrapper = update_wrapper(wrapper=wrapper, wrapped=func)
    return wrapper 
Example #4
Source File: __init__.py    From django-subadmin with MIT License 6 votes vote down vote up
def get_urls(self):
        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        base_viewname = self.get_base_viewname()

        urlpatterns = [
            path('' , include(self.get_subadmin_urls())),
            path('', wrap(self.changelist_view), name='%s_changelist' % base_viewname),
            path('add/', wrap(self.add_view), name='%s_add' % base_viewname),
            re_path(r'^(.+)/history/$', wrap(self.history_view), name='%s_history' % base_viewname),
            re_path(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_delete' % base_viewname),
            re_path(r'^(.+)/change/$', wrap(self.change_view), name='%s_change' % base_viewname),
        ]

        urlpatterns =  urlpatterns
        return urlpatterns 
Example #5
Source File: commands.py    From uplink with MIT License 6 votes vote down vote up
def __call__(
        self, func, request_definition_builder_factory=RequestDefinitionBuilder
    ):
        spec = utils.get_arg_spec(func)
        arg_handler = arguments.ArgumentAnnotationHandlerBuilder(
            func, spec.args
        )
        builder = request_definition_builder_factory(
            self._method,
            URIDefinitionBuilder(self._uri),
            arg_handler,
            decorators.MethodAnnotationHandlerBuilder(),
        )

        # Need to add the annotations after constructing the request
        # definition builder so it has a chance to attach its listener.
        arg_handler.set_annotations(spec.annotations)

        # Use return value type hint as expected return type
        if spec.return_annotation is not None:
            builder = returns.schema(spec.return_annotation)(builder)
        functools.update_wrapper(builder, func)
        builder = self._add_args(builder)
        return builder 
Example #6
Source File: langhelpers.py    From jbox with MIT License 6 votes vote down vote up
def decorator(target):
    """A signature-matching decorator factory."""

    def decorate(fn):
        if not inspect.isfunction(fn):
            raise Exception("not a decoratable function")
        spec = compat.inspect_getfullargspec(fn)
        names = tuple(spec[0]) + spec[1:3] + (fn.__name__,)
        targ_name, fn_name = _unique_symbols(names, 'target', 'fn')

        metadata = dict(target=targ_name, fn=fn_name)
        metadata.update(format_argspec_plus(spec, grouped=False))
        metadata['name'] = fn.__name__
        code = """\
def %(name)s(%(args)s):
    return %(target)s(%(fn)s, %(apply_kw)s)
""" % metadata
        decorated = _exec_code_in_env(code,
                                      {targ_name: target, fn_name: fn},
                                      fn.__name__)
        decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__
        decorated.__wrapped__ = fn
        return update_wrapper(decorated, fn)
    return update_wrapper(decorate, target) 
Example #7
Source File: langhelpers.py    From jbox with MIT License 6 votes vote down vote up
def memoized_instancemethod(fn):
    """Decorate a method memoize its return value.

    Best applied to no-arg methods: memoization is not sensitive to
    argument values, and will always return the same value even when
    called with different arguments.

    """

    def oneshot(self, *args, **kw):
        result = fn(self, *args, **kw)
        memo = lambda *a, **kw: result
        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        return result
    return update_wrapper(oneshot, fn) 
Example #8
Source File: wrappers.py    From jbox with MIT License 6 votes vote down vote up
def application(cls, f):
        """Decorate a function as responder that accepts the request as first
        argument.  This works like the :func:`responder` decorator but the
        function is passed the request object as first argument and the
        request object will be closed automatically::

            @Request.application
            def my_wsgi_app(request):
                return Response('Hello World!')

        :param f: the WSGI callable to decorate
        :return: a new WSGI callable
        """
        #: return a callable that wraps the -2nd argument with the request
        #: and calls the function with all the arguments up to that one and
        #: the request.  The return value is then called with the latest
        #: two arguments.  This makes it possible to use this decorator for
        #: both methods and standalone WSGI functions.
        def application(*args):
            request = cls(args[-2])
            with request:
                return f(*args[:-2] + (request,))(*args[-2:])
        return update_wrapper(application, f) 
Example #9
Source File: formparser.py    From jbox with MIT License 6 votes vote down vote up
def exhaust_stream(f):
    """Helper decorator for methods that exhausts the stream on return."""

    def wrapper(self, stream, *args, **kwargs):
        try:
            return f(self, stream, *args, **kwargs)
        finally:
            exhaust = getattr(stream, 'exhaust', None)
            if exhaust is not None:
                exhaust()
            else:
                while 1:
                    chunk = stream.read(1024 * 64)
                    if not chunk:
                        break
    return update_wrapper(wrapper, f) 
Example #10
Source File: core.py    From jbox with MIT License 5 votes vote down vote up
def resultcallback(self, replace=False):
        """Adds a result callback to the chain command.  By default if a
        result callback is already registered this will chain them but
        this can be disabled with the `replace` parameter.  The result
        callback is invoked with the return value of the subcommand
        (or the list of return values from all subcommands if chaining
        is enabled) as well as the parameters as they would be passed
        to the main callback.

        Example::

            @click.group()
            @click.option('-i', '--input', default=23)
            def cli(input):
                return 42

            @cli.resultcallback()
            def process_result(result, input):
                return result + input

        .. versionadded:: 3.0

        :param replace: if set to `True` an already existing result
                        callback will be removed.
        """
        def decorator(f):
            old_callback = self.result_callback
            if old_callback is None or replace:
                self.result_callback = f
                return f
            def function(__value, *args, **kwargs):
                return f(old_callback(__value, *args, **kwargs),
                         *args, **kwargs)
            self.result_callback = rv = update_wrapper(function, f)
            return rv
        return decorator 
Example #11
Source File: asyncsupport.py    From recruit with Apache License 2.0 5 votes vote down vote up
def wrap_render_func(original_render):
    def render(self, *args, **kwargs):
        if not self.environment.is_async:
            return original_render(self, *args, **kwargs)
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(self.render_async(*args, **kwargs))
    return update_wrapper(render, original_render) 
Example #12
Source File: asyncsupport.py    From recruit with Apache License 2.0 5 votes vote down vote up
def wrap_generate_func(original_generate):
    def _convert_generator(self, loop, args, kwargs):
        async_gen = self.generate_async(*args, **kwargs)
        try:
            while 1:
                yield loop.run_until_complete(async_gen.__anext__())
        except StopAsyncIteration:
            pass
    def generate(self, *args, **kwargs):
        if not self.environment.is_async:
            return original_generate(self, *args, **kwargs)
        return _convert_generator(self, asyncio.get_event_loop(), args, kwargs)
    return update_wrapper(generate, original_generate) 
Example #13
Source File: core.py    From recruit with Apache License 2.0 5 votes vote down vote up
def resultcallback(self, replace=False):
        """Adds a result callback to the chain command.  By default if a
        result callback is already registered this will chain them but
        this can be disabled with the `replace` parameter.  The result
        callback is invoked with the return value of the subcommand
        (or the list of return values from all subcommands if chaining
        is enabled) as well as the parameters as they would be passed
        to the main callback.

        Example::

            @click.group()
            @click.option('-i', '--input', default=23)
            def cli(input):
                return 42

            @cli.resultcallback()
            def process_result(result, input):
                return result + input

        .. versionadded:: 3.0

        :param replace: if set to `True` an already existing result
                        callback will be removed.
        """
        def decorator(f):
            old_callback = self.result_callback
            if old_callback is None or replace:
                self.result_callback = f
                return f
            def function(__value, *args, **kwargs):
                return f(old_callback(__value, *args, **kwargs),
                         *args, **kwargs)
            self.result_callback = rv = update_wrapper(function, f)
            return rv
        return decorator 
Example #14
Source File: decorators.py    From jbox with MIT License 5 votes vote down vote up
def pass_context(f):
    """Marks a callback as wanting to receive the current context
    object as first argument.
    """
    def new_func(*args, **kwargs):
        return f(get_current_context(), *args, **kwargs)
    return update_wrapper(new_func, f) 
Example #15
Source File: cli.py    From jbox with MIT License 5 votes vote down vote up
def with_appcontext(f):
    """Wraps a callback so that it's guaranteed to be executed with the
    script's application context.  If callbacks are registered directly
    to the ``app.cli`` object then they are wrapped with this function
    by default unless it's disabled.
    """
    @click.pass_context
    def decorator(__ctx, *args, **kwargs):
        with __ctx.ensure_object(ScriptInfo).load_app().app_context():
            return __ctx.invoke(f, *args, **kwargs)
    return update_wrapper(decorator, f) 
Example #16
Source File: wsgi.py    From jbox with MIT License 5 votes vote down vote up
def responder(f):
    """Marks a function as responder.  Decorate a function with it and it
    will automatically call the return value as WSGI application.

    Example::

        @responder
        def application(environ, start_response):
            return Response('Hello World!')
    """
    return update_wrapper(lambda *a: f(*a)(*a[-2:]), f) 
Example #17
Source File: _compat.py    From jbox with MIT License 5 votes vote down vote up
def native_string_result(func):
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs).encode('utf-8')
        return functools.update_wrapper(wrapper, func) 
Example #18
Source File: decorators.py    From jbox with MIT License 5 votes vote down vote up
def make_pass_decorator(object_type, ensure=False):
    """Given an object type this creates a decorator that will work
    similar to :func:`pass_obj` but instead of passing the object of the
    current context, it will find the innermost context of type
    :func:`object_type`.

    This generates a decorator that works roughly like this::

        from functools import update_wrapper

        def decorator(f):
            @pass_context
            def new_func(ctx, *args, **kwargs):
                obj = ctx.find_object(object_type)
                return ctx.invoke(f, obj, *args, **kwargs)
            return update_wrapper(new_func, f)
        return decorator

    :param object_type: the type of the object to pass.
    :param ensure: if set to `True`, a new object will be created and
                   remembered on the context if it's not there yet.
    """
    def decorator(f):
        def new_func(*args, **kwargs):
            ctx = get_current_context()
            if ensure:
                obj = ctx.ensure_object(object_type)
            else:
                obj = ctx.find_object(object_type)
            if obj is None:
                raise RuntimeError('Managed to invoke callback without a '
                                   'context object of type %r existing'
                                   % object_type.__name__)
            return ctx.invoke(f, obj, *args[1:], **kwargs)
        return update_wrapper(new_func, f)
    return decorator 
Example #19
Source File: functools_lru_cache.py    From aegea with Apache License 2.0 5 votes vote down vote up
def update_wrapper(wrapper,
                   wrapped,
                   assigned = functools.WRAPPER_ASSIGNMENTS,
                   updated = functools.WRAPPER_UPDATES):
    """
    Patch two bugs in functools.update_wrapper.
    """
    # workaround for http://bugs.python.org/issue3445
    assigned = tuple(attr for attr in assigned if hasattr(wrapped, attr))
    wrapper = functools.update_wrapper(wrapper, wrapped, assigned, updated)
    # workaround for https://bugs.python.org/issue17482
    wrapper.__wrapped__ = wrapped
    return wrapper 
Example #20
Source File: decorators.py    From recruit with Apache License 2.0 5 votes vote down vote up
def pass_obj(f):
    """Similar to :func:`pass_context`, but only pass the object on the
    context onwards (:attr:`Context.obj`).  This is useful if that object
    represents the state of a nested system.
    """
    def new_func(*args, **kwargs):
        return f(get_current_context().obj, *args, **kwargs)
    return update_wrapper(new_func, f) 
Example #21
Source File: decorators.py    From recruit with Apache License 2.0 5 votes vote down vote up
def pass_context(f):
    """Marks a callback as wanting to receive the current context
    object as first argument.
    """
    def new_func(*args, **kwargs):
        return f(get_current_context(), *args, **kwargs)
    return update_wrapper(new_func, f) 
Example #22
Source File: base_request.py    From recruit with Apache License 2.0 5 votes vote down vote up
def application(cls, f):
        """Decorate a function as responder that accepts the request as first
        argument.  This works like the :func:`responder` decorator but the
        function is passed the request object as first argument and the
        request object will be closed automatically::

            @Request.application
            def my_wsgi_app(request):
                return Response('Hello World!')

        As of Werkzeug 0.14 HTTP exceptions are automatically caught and
        converted to responses instead of failing.

        :param f: the WSGI callable to decorate
        :return: a new WSGI callable
        """
        #: return a callable that wraps the -2nd argument with the request
        #: and calls the function with all the arguments up to that one and
        #: the request.  The return value is then called with the latest
        #: two arguments.  This makes it possible to use this decorator for
        #: both methods and standalone WSGI functions.
        from ..exceptions import HTTPException

        def application(*args):
            request = cls(args[-2])
            with request:
                try:
                    resp = f(*args[:-2] + (request,))
                except HTTPException as e:
                    resp = e.get_response(args[-2])
                return resp(*args[-2:])

        return update_wrapper(application, f) 
Example #23
Source File: _compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def native_string_result(func):
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs).encode("utf-8")

        return functools.update_wrapper(wrapper, func) 
Example #24
Source File: local.py    From recruit with Apache License 2.0 5 votes vote down vote up
def middleware(self, func):
        """Like `make_middleware` but for decorating functions.

        Example usage::

            @manager.middleware
            def application(environ, start_response):
                ...

        The difference to `make_middleware` is that the function passed
        will have all the arguments copied from the inner application
        (name, docstring, module).
        """
        return update_wrapper(self.make_middleware(func), func) 
Example #25
Source File: cli.py    From recruit with Apache License 2.0 5 votes vote down vote up
def with_appcontext(f):
    """Wraps a callback so that it's guaranteed to be executed with the
    script's application context.  If callbacks are registered directly
    to the ``app.cli`` object then they are wrapped with this function
    by default unless it's disabled.
    """
    @click.pass_context
    def decorator(__ctx, *args, **kwargs):
        with __ctx.ensure_object(ScriptInfo).load_app().app_context():
            return __ctx.invoke(f, *args, **kwargs)
    return update_wrapper(decorator, f) 
Example #26
Source File: blueprints.py    From recruit with Apache License 2.0 5 votes vote down vote up
def record_once(self, func):
        """Works like :meth:`record` but wraps the function in another
        function that will ensure the function is only called once.  If the
        blueprint is registered a second time on the application, the
        function passed is not called.
        """
        def wrapper(state):
            if state.first_registration:
                func(state)
        return self.record(update_wrapper(wrapper, func)) 
Example #27
Source File: app.py    From recruit with Apache License 2.0 5 votes vote down vote up
def setupmethod(f):
    """Wraps a method so that it performs a check in debug mode if the
    first request was already handled.
    """
    def wrapper_func(self, *args, **kwargs):
        if self.debug and self._got_first_request:
            raise AssertionError('A setup function was called after the '
                'first request was handled.  This usually indicates a bug '
                'in the application where a module was not imported '
                'and decorators or other functionality was called too late.\n'
                'To fix this make sure to import all your view modules, '
                'database models and everything related at a central place '
                'before the application starts serving requests.')
        return f(self, *args, **kwargs)
    return update_wrapper(wrapper_func, f) 
Example #28
Source File: asyncsupport.py    From recruit with Apache License 2.0 5 votes vote down vote up
def patch_template():
    from jinja2 import Template
    Template.generate = wrap_generate_func(Template.generate)
    Template.generate_async = update_wrapper(
        generate_async, Template.generate_async)
    Template.render_async = update_wrapper(
        render_async, Template.render_async)
    Template.render = wrap_render_func(Template.render)
    Template._get_default_module = wrap_default_module(
        Template._get_default_module)
    Template._get_default_module_async = get_default_module_async
    Template.make_module_async = update_wrapper(
        make_module_async, Template.make_module_async) 
Example #29
Source File: asyncsupport.py    From recruit with Apache License 2.0 5 votes vote down vote up
def wrap_macro_invoke(original_invoke):
    @internalcode
    async def async_invoke(self, arguments, autoescape):
        rv = await self._func(*arguments)
        if autoescape:
            rv = Markup(rv)
        return rv

    @internalcode
    def _invoke(self, arguments, autoescape):
        if not self._environment.is_async:
            return original_invoke(self, arguments, autoescape)
        return async_invoke(self, arguments, autoescape)
    return update_wrapper(_invoke, original_invoke) 
Example #30
Source File: asyncsupport.py    From recruit with Apache License 2.0 5 votes vote down vote up
def wrap_block_reference_call(original_call):
    @internalcode
    async def async_call(self):
        rv = await concat_async(self._stack[self._depth](self._context))
        if self._context.eval_ctx.autoescape:
            rv = Markup(rv)
        return rv

    @internalcode
    def __call__(self):
        if not self._context.environment.is_async:
            return original_call(self)
        return async_call(self)

    return update_wrapper(__call__, original_call)