Esempio n. 1
0
    def test_typechecked_no_annotations(self, recwarn):
        def foo(a, b):
            pass

        typechecked(foo)

        func_name = function_name(foo)
        assert len(recwarn) == 1
        assert str(recwarn[0].message) == (
            'no type annotations present -- not typechecking {}'.format(func_name))
Esempio n. 2
0
 def __new__(cls, name: str, bases: Any,
             dct: Dict[Any, Any]) -> type:  # type: ignore
     newly = super().__new__(cls, name, bases, dct)
     if _has_type_annotations(newly.__init__):  # type: ignore
         newly.__init__ = typechecked(always=True)(
             newly.__init__)  # type: ignore
     if hasattr(newly, '__call__') and _has_type_annotations(
             newly.__call__):
         newly.__call__ = typechecked(always=True)(
             newly.__call__)  # type: ignore
     if hasattr(newly, 'can_process') and _has_type_annotations(
             newly.can_process):  # type: ignore
         newly.can_process = typechecked(always=True)(
             newly.can_process)  # type: ignore
     return newly
Esempio n. 3
0
def typechecked_compatible(function):
    """Turns off type checking for old incompatible python versions.

    Mainly for new syntax like list[str] which raise TypeError.
    """
    if sys.version_info.minor < 9:
        return function
    return typechecked(function)
Esempio n. 4
0
    def register_method(self, method_name: str, func: Callable):
        """
        Register FastRPC method

        :param method_name:     Name of the method - how it will be called from the outside
        :param func:            The function that will handle that call
        """
        if self.enforce_types:
            self.methods[method_name] = typechecked(func)
        else:
            self.methods[method_name] = func
Esempio n. 5
0
    def register_method(self, method_name: str, func: Callable):
        """
        Register FastRPC method

        :param method_name:     Name of the method - how it will be called from the outside
        :param func:            The function that will handle that call
        """
        if self.enforce_types:
            self.methods[method_name] = typechecked(func)
        else:
            self.methods[method_name] = func
Esempio n. 6
0
    def typecheck_wrap(*args: Any, **kwargs: Any) -> Any:

        from hpc.autoscale.node.node import Node  # noqa
        from hpc.autoscale.node.bucket import NodeBucket  # noqa

        from hpc.autoscale.job.job import Job  # noqa

        # let's not require that this is installed unless
        # they turn on runtime type checking
        from typeguard import typechecked

        return typechecked(function)(*args, **kwargs)
Esempio n. 7
0
 def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
     method_name = fn.__name__ if not name else name
     if validate and not self._validate(fn):
         raise ValueError('no type annotations present to: {0}'.format(method_name))
     fn_annotations = get_type_hints(fn)
     fn.jsonrpc_method_name = method_name  # type: ignore
     fn.jsonrpc_method_sig = fn_annotations  # type: ignore
     fn.jsonrpc_method_return = fn_annotations.pop('return', None)  # type: ignore
     fn.jsonrpc_method_params = fn_annotations  # type: ignore
     fn.jsonrpc_validate = validate  # type: ignore
     fn.jsonrpc_options = options  # type: ignore
     fn_wrapped = typechecked(fn) if validate else fn
     self.get_jsonrpc_site().register(method_name, fn_wrapped)
     return fn_wrapped
 def register_view_function(self,
                            view_func: Callable[..., Any],
                            name: Optional[str] = None,
                            validate: bool = True,
                            **options: Any) -> Callable[..., Any]:
     fn = self._get_function(view_func)
     fn_annotations = get_type_hints(fn)
     method_name = getattr(fn, '__name__', '<noname>') if not name else name
     setattr(fn, 'jsonrpc_method_name', method_name)
     setattr(fn, 'jsonrpc_method_sig', fn_annotations)
     setattr(fn, 'jsonrpc_method_return',
             fn_annotations.pop('return', None))
     setattr(fn, 'jsonrpc_method_params', fn_annotations)
     setattr(fn, 'jsonrpc_validate', validate)
     setattr(fn, 'jsonrpc_options', options)
     view_func_wrapped = typechecked(view_func) if validate else view_func
     self.get_jsonrpc_site().register(method_name, view_func_wrapped)
     return view_func_wrapped
Esempio n. 9
0
    def __call__(cls, *args, **kwargs):
        """this is called every time we create an instance of the class
        """

        #========================================
        # Enforce instance attribute types

        if args:
            raise ValueError("Only Keyword Argumetns are accepted")

        sig = signature(cls.__init__)
        for kw in kwargs:
            if not kwargs.get(kw, False):
                raise AttributeError(f"Must set attribute: <{kw}>")

        model_dict = {
            kw: (sig.parameters[kw].annotation, ...)
            for kw in kwargs
        }
        Model = create_model("Test", **model_dict)

        try:
            validated = Model(**{kw: val for kw, val in kwargs.items()})
            kwargs = validated.dict()
        except ValidationError as e:
            raise e
        except Exception as e:
            raise e

        #========================================
        # Enforce instance method annotations

        # get only functions defined in class that are not builtins
        funcs = {
            k: v
            for k, v in dict(inspect.getmembers(cls)).items()
            if not k.startswith("__") and callable(v)
        }
        # wrap every user function with <typechecked> decorator
        for name, obj in funcs.items():
            setattr(cls, name, typechecked(obj))

        return super().__call__(*args, **kwargs)
Esempio n. 10
0
 def wrapped(self):
     if self._wrapped is None:
         self._wrapped = typeguard.typechecked(self.func)
     return self._wrapped
Esempio n. 11
0
 def get_typechecked_f_and_hintcount(f):
     hintcount = get_type_hint_count(f)
     typechecked_f = typechecked(f, always=True)
     return typechecked_f, hintcount
Esempio n. 12
0
 def decorator(*args: Tuple[Any, ...], **kwargs: Any) -> type:
     if prohibit_args:
         check_args(*args, **kwargs)
     return typechecked(decorated)(*args, **kwargs)
Esempio n. 13
0
 def __init__(self) -> None:
     self.pull = typechecked(always=True)(self.pull)  # type: ignore