File: __init__.py

package info (click to toggle)
knot-resolver 6.0.17-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 16,376 kB
  • sloc: javascript: 42,732; ansic: 40,311; python: 12,580; cpp: 2,121; sh: 1,988; xml: 193; makefile: 181
file content (44 lines) | stat: -rw-r--r-- 1,604 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from typing import Any, Callable, Optional, Type, TypeVar

T = TypeVar("T")


def ignore_exceptions_optional(
    _tp: Type[T], default: Optional[T], *exceptions: Type[BaseException]
) -> Callable[[Callable[..., Optional[T]]], Callable[..., Optional[T]]]:
    """
    Decorator, that wraps around a function preventing it from raising exceptions
    and instead returning the configured default value.

    :param Type[T] _tp: Return type of the function. Essentialy only a template argument for type-checking
    :param T default: The value to return as a default
    :param List[Type[BaseException]] exceptions: The list of exceptions to catch
    :return: value of the decorated function, or default if exception raised
    :rtype: T
    """

    def decorator(func: Callable[..., Optional[T]]) -> Callable[..., Optional[T]]:
        def f(*nargs: Any, **nkwargs: Any) -> Optional[T]:
            try:
                return func(*nargs, **nkwargs)
            except BaseException as e:
                if isinstance(e, exceptions):
                    return default
                raise e

        return f

    return decorator


def ignore_exceptions(
    default: T, *exceptions: Type[BaseException]
) -> Callable[[Callable[..., Optional[T]]], Callable[..., Optional[T]]]:
    return ignore_exceptions_optional(type(default), default, *exceptions)


def phantom_use(var: Any) -> None:  # pylint: disable=unused-argument
    """
    Function, which consumes its argument doing absolutely nothing with it. Useful
    for convincing pylint, that we need the variable even when its unused.
    """