Python typing.Callable() Examples

The following are 30 code examples of typing.Callable(). 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 typing , or try the search function .
Example #1
Source File: event_dispatcher.py    From clikit with MIT License 7 votes vote down vote up
def get_listeners(
        self, event_name=None
    ):  # type: (str) -> Union[List[Callable], Dict[str, Callable]]
        if event_name is not None:
            if event_name not in self._listeners:
                return []

            if event_name not in self._sorted:
                self._sort_listeners(event_name)

            return self._sorted[event_name]

        for event_name, event_listeners in self._listeners.items():
            if event_name not in self._sorted:
                self._sort_listeners(event_name)

        return self._sorted 
Example #2
Source File: util.py    From cmus-osx with MIT License 7 votes vote down vote up
def throttle(interval: Union[float, int]):
    """Decorator ensures function that can only be called once every `s` seconds.
    """

    def decorate(fn: Callable) -> Callable:
        t = None

        def wrapped(*args, **kwargs):
            nonlocal t
            t_ = time()
            if t is None or t_ - t >= interval:
                result = fn(*args, **kwargs)
                t = time()
                return result

        return wrapped

    return decorate 
Example #3
Source File: blueprints.py    From quart with MIT License 7 votes vote down vote up
def register_error_handler(self, error: Union[Type[Exception], int], func: Callable) -> None:
        """Add an error handler function to the blueprint.

        This is designed to be used on the blueprint directly, and
        has the same arguments as
        :meth:`~quart.Quart.register_error_handler`. An example usage,

        .. code-block:: python

            def not_found():
                ...

            blueprint = Blueprint(__name__)
            blueprint.register_error_handler(404, not_found)
        """
        self.record_once(lambda state: state.app.register_error_handler(error, func, self.name)) 
Example #4
Source File: predicate.py    From python-clean-architecture with MIT License 7 votes vote down vote up
def test(self, func: t.Callable[..., bool], *args, **kwargs) -> Predicate:
        """
        Run a user-defined test function against the value.
        >>> def test_func(val):
        ...     return val == 42
        ...
        >>> var('f1').test(test_func)

        :param func: The function to call, passing the dict as the first
            argument
        :param args:
        :param kwargs:
            Additional arguments to pass to the test function
        """
        return self._build_predicate(
            lambda lhs, value: func(lhs, *args, **kwargs),
            Operation.TEST,
            (self._path, func, args, freeze(kwargs))
        ) 
Example #5
Source File: file_utils.py    From cmrc2019 with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def s3_request(func: Callable):
    """
    Wrapper function for s3 requests in order to create more helpful error
    messages.
    """

    @wraps(func)
    def wrapper(url: str, *args, **kwargs):
        try:
            return func(url, *args, **kwargs)
        except ClientError as exc:
            if int(exc.response["Error"]["Code"]) == 404:
                raise FileNotFoundError("file {} not found".format(url))
            else:
                raise

    return wrapper 
Example #6
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def teardown_request(self, func: Callable) -> Callable:
        """Add a teardown request function to the Blueprint.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.teardown_request`. It applies only to requests that
        are routed to an endpoint in this blueprint. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.teardown_request
            def teardown():
                ...
        """
        self.record_once(lambda state: state.app.teardown_request(func, self.name))
        return func 
Example #7
Source File: operators.py    From python-clean-architecture with MIT License 6 votes vote down vote up
def check_path(
    test: t.Callable[[t.Any, t.Any], bool],
    path: t.Iterable[str]
) -> t.Callable[..., bool]:
    def check_path_curried(value):
        orig_value = value
        for part in path:
            try:
                value = getattr(value, part)
            except AttributeError:
                try:
                    value = value[part]
                except (KeyError, TypeError):
                    return False
        return test(value, orig_value)

    return check_path_curried 
Example #8
Source File: views.py    From quart with MIT License 6 votes vote down vote up
def as_view(cls, name: str, *class_args: Any, **class_kwargs: Any) -> Callable:
        async def view(*args: Any, **kwargs: Any) -> Callable:
            self = view.view_class(*class_args, **class_kwargs)  # type: ignore
            return await self.dispatch_request(*args, **kwargs)

        if cls.decorators:
            view.__name__ = name
            view.__module__ = cls.__module__
            for decorator in cls.decorators:
                view = decorator(view)

        view.view_class: View = cls  # type: ignore
        view.__name__ = name
        view.__doc__ = cls.__doc__
        view.__module__ = cls.__module__
        view.methods = cls.methods  # type: ignore
        view.provide_automatic_options = cls.provide_automatic_options  # type: ignore
        return view 
Example #9
Source File: utils.py    From pypika with Apache License 2.0 6 votes vote down vote up
def builder(func: Callable) -> Callable:
    """
    Decorator for wrapper "builder" functions.  These are functions on the Query class or other classes used for
    building queries which mutate the query and return self.  To make the build functions immutable, this decorator is
    used which will deepcopy the current instance.  This decorator will return the return value of the inner function
    or the new copy of the instance.  The inner function does not need to return self.
    """
    import copy

    def _copy(self, *args, **kwargs):
        self_copy = copy.copy(self) if getattr(self, "immutable", True) else self
        result = func(self_copy, *args, **kwargs)

        # Return self if the inner function returns None.  This way the inner function can return something
        # different (for example when creating joins, a different builder is returned).
        if result is None:
            return self_copy

        return result

    return _copy 
Example #10
Source File: utils.py    From pypika with Apache License 2.0 6 votes vote down vote up
def ignore_copy(func: Callable) -> Callable:
    """
    Decorator for wrapping the __getattr__ function for classes that are copied via deepcopy.  This prevents infinite
    recursion caused by deepcopy looking for magic functions in the class. Any class implementing __getattr__ that is
    meant to be deepcopy'd should use this decorator.

    deepcopy is used by pypika in builder functions (decorated by @builder) to make the results immutable.  Any data
    model type class (stored in the Query instance) is copied.
    """

    def _getattr(self, name):
        if name in [
            "__copy__",
            "__deepcopy__",
            "__getstate__",
            "__setstate__",
            "__getnewargs__",
        ]:
            raise AttributeError(
                  "'%s' object has no attribute '%s'" % (self.__class__.__name__, name)
            )

        return func(self, name)

    return _getattr 
Example #11
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def app_url_value_preprocessor(self, func: Callable) -> Callable:
        """Add a url value preprocessor.

        This is designed to be used as a decorator, and has the same
        arguments as
        :meth:`~quart.Quart.app_url_value_preprocessor`. This will
        apply to all URLs. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.app_url_value_preprocessor
            def processor(endpoint, view_args):
                ...

        """
        self.record_once(lambda state: state.app.url_value_preprocessor(func))
        return func 
Example #12
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def url_value_preprocessor(self, func: Callable) -> Callable:
        """Add a url value preprocessor.

        This is designed to be used as a decorator, and has the same
        arguments as :meth:`~quart.Quart.url_value_preprocessor`. This
        will apply to urls in this blueprint. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.url_value_preprocessor
            def processor(endpoint, view_args):
                ...

        """
        self.record_once(lambda state: state.app.url_value_preprocessor(func, self.name))
        return func 
Example #13
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def context_processor(self, func: Callable) -> Callable:
        """Add a context processor function to this blueprint.

        This is designed to be used as a decorator, and has the same
        arguments as :meth:`~quart.Quart.context_processor`. This will
        add context to all templates rendered in this blueprint's
        routes. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.context_processor
            def processor():
                ...
        """
        self.record_once(lambda state: state.app.context_processor(func, self.name))
        return func 
Example #14
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def app_errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
        """Add an error handler function to the App.

        This is designed to be used as a decorator, and has the same
        arguments as :meth:`~quart.Quart.errorhandler`. It applies
        only to all errors. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.app_errorhandler(404)
            def not_found():
                ...
        """

        def decorator(func: Callable) -> Callable:
            self.record_once(lambda state: state.app.register_error_handler(error, func))
            return func

        return decorator 
Example #15
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def errorhandler(self, error: Union[Type[Exception], int]) -> Callable:
        """Add an error handler function to the Blueprint.

        This is designed to be used as a decorator, and has the same
        arguments as :meth:`~quart.Quart.errorhandler`. It applies
        only to errors that originate in routes in this blueprint. An
        example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.errorhandler(404)
            def not_found():
                ...

        """

        def decorator(func: Callable) -> Callable:
            self.register_error_handler(error, func)
            return func

        return decorator 
Example #16
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def teardown_app_request(self, func: Callable) -> Callable:
        """Add a teardown request function to the app.

        This is designed to be used as a decorator, and has the same
        arguments as :meth:`~quart.Quart.teardown_request`. It applies
        to all requests to the app this blueprint is registered on. An
        example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.teardown_app_request
            def teardown():
                ...
        """
        self.record_once(lambda state: state.app.teardown_request(func))
        return func 
Example #17
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def endpoint(self, endpoint: str) -> Callable:
        """Add an endpoint to the blueprint.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.endpoint`. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.endpoint('index')
            def index():
                ...
        """

        def decorator(func: Callable) -> Callable:
            self.record_once(lambda state: state.register_endpoint(endpoint, func))
            return func

        return decorator 
Example #18
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def app_template_filter(self, name: Optional[str] = None) -> Callable:
        """Add an application wide template filter.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.template_filter`. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.app_template_filter()
            def filter(value):
                ...
        """

        def decorator(func: Callable) -> Callable:
            self.add_app_template_filter(func, name=name)
            return func

        return decorator 
Example #19
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def add_app_template_filter(self, func: Callable, name: Optional[str] = None) -> None:
        """Add an application wide template filter.

        This is designed to be used on the blueprint directly, and
        has the same arguments as
        :meth:`~quart.Quart.add_template_filter`. An example usage,

        .. code-block:: python

            def filter():
                ...

            blueprint = Blueprint(__name__)
            blueprint.add_app_template_filter(filter)
        """
        self.record_once(lambda state: state.register_template_filter(func, name)) 
Example #20
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def app_template_test(self, name: Optional[str] = None) -> Callable:
        """Add an application wide template test.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.template_test`. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.app_template_test()
            def test(value):
                ...
        """

        def decorator(func: Callable) -> Callable:
            self.add_app_template_test(func, name=name)
            return func

        return decorator 
Example #21
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def add_app_template_test(self, func: Callable, name: Optional[str] = None) -> None:
        """Add an application wide template test.

        This is designed to be used on the blueprint directly, and
        has the same arguments as
        :meth:`~quart.Quart.add_template_test`. An example usage,

        .. code-block:: python

            def test():
                ...

            blueprint = Blueprint(__name__)
            blueprint.add_app_template_test(test)
        """
        self.record_once(lambda state: state.register_template_test(func, name)) 
Example #22
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def add_app_template_global(self, func: Callable, name: Optional[str] = None) -> None:
        """Add an application wide template global.

        This is designed to be used on the blueprint directly, and
        has the same arguments as
        :meth:`~quart.Quart.add_template_global`. An example usage,

        .. code-block:: python

            def global():
                ...

            blueprint = Blueprint(__name__)
            blueprint.add_app_template_global(global)
        """
        self.record_once(lambda state: state.register_template_global(func, name)) 
Example #23
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def before_request(self, func: Callable) -> Callable:
        """Add a before request function to the Blueprint.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.before_request`. It applies only to requests that
        are routed to an endpoint in this blueprint. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.before_request
            def before():
                ...
        """
        self.record_once(lambda state: state.app.before_request(func, self.name))
        return func 
Example #24
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def before_websocket(self, func: Callable) -> Callable:
        """Add a before request websocket to the Blueprint.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.before_websocket`. It applies only to requests that
        are routed to an endpoint in this blueprint. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.before_websocket
            def before():
                ...

        """
        self.record_once(lambda state: state.app.before_websocket(func, self.name))
        return func 
Example #25
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def before_app_request(self, func: Callable) -> Callable:
        """Add a before request function to the app.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.before_request`. It applies to all requests to the
        app this blueprint is registered on. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.before_app_request
            def before():
                ...
        """
        self.record_once(lambda state: state.app.before_request(func))
        return func 
Example #26
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def before_app_websocket(self, func: Callable) -> Callable:
        """Add a before request websocket to the App.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
        app this blueprint is registered on. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.before_app_websocket
            def before():
                ...

        """
        self.record_once(lambda state: state.app.before_websocket(func))
        return func 
Example #27
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def after_request(self, func: Callable) -> Callable:
        """Add an after request function to the Blueprint.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.after_request`. It applies only to requests that
        are routed to an endpoint in this blueprint. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.after_request
            def after():
                ...
        """
        self.record_once(lambda state: state.app.after_request(func, self.name))
        return func 
Example #28
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def after_websocket(self, func: Callable) -> Callable:
        """Add an after websocket function to the Blueprint.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.after_websocket`. It applies only to requests that
        are routed to an endpoint in this blueprint. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.after_websocket
            def after():
                ...
        """
        self.record_once(lambda state: state.app.after_websocket(func, self.name))
        return func 
Example #29
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def after_app_request(self, func: Callable) -> Callable:
        """Add a after request function to the app.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.after_request`. It applies to all requests to the
        app this blueprint is registered on. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.after_app_request
            def after():
                ...
        """
        self.record_once(lambda state: state.app.after_request(func))
        return func 
Example #30
Source File: blueprints.py    From quart with MIT License 6 votes vote down vote up
def after_app_websocket(self, func: Callable) -> Callable:
        """Add an after websocket function to the App.

        This is designed to be used as a decorator, and has the same arguments
        as :meth:`~quart.Quart.after_websocket`. It applies to all requests to the
        ppe this blueprint is registerd on. An example usage,

        .. code-block:: python

            blueprint = Blueprint(__name__)
            @blueprint.after_app_websocket
            def after():
                ...
        """
        self.record_once(lambda state: state.app.after_websocket(func))
        return func