from knot_resolver_manager import compat
from knot_resolver_manager.constants import LISTEN_SOCKET_PATH, MANAGER_CONFIG_FILE
from knot_resolver_manager.server import start_server
-from knot_resolver_manager.utils import ignore_exceptions
+from knot_resolver_manager.utils import ignore_exceptions_optional
@click.command()
if listen is None:
unix.append(LISTEN_SOCKET_PATH)
else:
- port = ignore_exceptions(None, ValueError)(int)(listen)
+ port = ignore_exceptions_optional(int, None, ValueError)(int)(listen)
if port is not None:
tcp.append(("localhost", port))
else:
T = TypeVar("T")
-def ignore_exceptions(
- default: Optional[T], *exceptions: Type[BaseException]
+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 decorator
+def ignore_exceptions(
+ default: T, *exceptions: Type[BaseException]
+) -> Callable[[Callable[..., Optional[T]]], Callable[..., Optional[T]]]:
+ return ignore_exceptions_optional(type(default), default, *exceptions)
+
+
__all__ = [
+ "ignore_exceptions_optional",
"ignore_exceptions",
"types",
"DataclassParserValidatorMixin",
def is_optional(tp: Any) -> bool:
origin = getattr(tp, "__origin__", None)
- args = getattr(tp, "__args__", [])
+ args = get_generic_type_arguments(tp)
return origin == Union and len(args) == 2 and args[1] == NoneType
def get_generic_type_arguments(tp: Any) -> List[Any]:
- return list(getattr(tp, "__args__", []))
+ default: List[Any] = []
+ return getattr(tp, "__args__", default)
def get_generic_type_argument(tp: Any) -> Any: