Check arguments type, raise :class:`TypeError` if argument type is not
    expected type.

    :param c: callable object want to check types
    :param hints: assumed type of given ``c`` result of
                  :func:`typing.get_type_hints`
507767
def check_arguments(c: typing.Callable,
                    hints: typing.Mapping[str, typing.Optional[type]],
                    *args, **kwargs) -> None:
    
    signature = inspect.signature(c)
    bound = signature.bind(*args, **kwargs)
    for argument_name, value in bound.arguments.items():
        try:
            type_hint = hints[argument_name]
        except KeyError:
            continue
        actual_type, correct = check_type(value, type_hint)
        if not correct:
            raise TypeError(
                'Incorrect type `{}`, expected `{}` for `{}`'.format(
                    actual_type, type_hint, argument_name
                )
            )
1123006
def __get_type_from_char(self, c):
        
        if c.isdigit() or c =='-':
            return ("number", False, None)
        elif c == 't' or c == 'f': ## true/false
            return ("boolean", False, None)
        elif c == 'n': ## nil
            return ("nil", False, None)
        elif c == '\\' :
            return ("char", False, None)
        elif c == ':':
            return ("keyword", False, None)
        elif c == '"':
            return ("string", False, None)
        elif c == '#':
            if self.__read_and_back(1) == '{':
                return ("set", True, "}")
            if self.__read_and_back(1) == ':':
                return ("namespaced_dict", True, "}")
            if self.__read_and_back(4) == 'inst':
                return ("datetime", False, None)
            if self.__read_and_back(4) == 'uuid':
                return ("uuid", False, None)
        elif c == '{':
            return ("dict", True, "}")
        elif c == '(':
            return ("list", True, ")")
        elif c == '[':
            return ('list', True, "]")

        return (None, False, None)
1010143
def checktype(self, val, kind, **kargs):
        """"""
        if not isinstance(val, kind):
            raise TypeError('Expected {}; got {}'.format(
                            self.str_kind(kind), self.str_valtype(val)))
270231
def _guess_type(val):
        """"""
        if isinstance(val, bool):
            return "choice"
        elif isinstance(val, int):
            return "number"
        elif isinstance(val, float):
            return "number"
        elif isinstance(val, str):
            return "text"
        elif hasattr(val, 'read'):
            return "file"
        else:
            return "text"
185956
def check_type(lineno, type_list, arg):
    
    if not isinstance(type_list, list):
        type_list = [type_list]

    if arg.type_ in type_list:
        return True

    if len(type_list) == 1:
        syntax_error(lineno, "Wrong expression type '%s'. Expected '%s'" %
                     (arg.type_, type_list[0]))
    else:
        syntax_error(lineno, "Wrong expression type '%s'. Expected one of '%s'"
                     % (arg.type_, tuple(type_list)))

    return False
333564
def check_argument_type(dtype, kernel_argument, i):
    """"""
    types_map = {"uint8": ["uchar", "unsigned char", "uint8_t"],
                 "int8": ["char", "int8_t"],
                 "uint16": ["ushort", "unsigned short", "uint16_t"],
                 "int16": ["short", "int16_t"],
                 "uint32": ["uint", "unsigned int", "uint32_t"],
                 "int32": ["int", "int32_t"],   #discrepancy between OpenCL and C here, long may be 32bits in C
                 "uint64": ["ulong", "unsigned long", "uint64_t"],
                 "int64": ["long", "int64_t"],
                 "float16": ["half"],
                 "float32": ["float"],
                 "float64": ["double"]}
    if dtype in types_map:
        return any([substr in kernel_argument for substr in types_map[dtype]])
    else:
        return False
875285
def _infer_type(value, element_kind, element_name):
    

    if value is None:
        raise ValueError(
            _format("Cannot infer CIM type of {0} {1!A} from its value when "
                    "the value is None", element_kind, element_name))

    try:
        return cimtype(value)
    except TypeError as exc:
        raise ValueError(
            _format("Cannot infer CIM type of {0} {1!A} from its value: {2!A}",
                    element_kind, element_name, exc))
934485
def check_types(func):
    
    call = PythonCall(func)

    @wraps(func)
    def decorator(*args, **kwargs):
        parameters = call.bind(args, kwargs)
        for arg_name, expected_type in func.__annotations__.items():
            if not isinstance(parameters[arg_name], expected_type):
                raise TypeError("{} must be a {}".format(
                    arg_name, expected_type))
        return call.apply(args, kwargs)
    return decorator
1149295
def _check_known_decorators(typ, calling_decorator  # type: str
                            ):
    # type: (...) -> bool
    
    for member in typ.__dict__.values():
        if hasattr(member, '__enforcer__'):
            raise AutoclassDecorationException('It seems that @runtime_validation decorator was applied to type <'
                                               + str(typ) + '> BEFORE ' + calling_decorator + '. This is not supported '
                                               'as it may lead to counter-intuitive behaviour, please change the order '
                                               'of the decorators on <' + str(typ) + '>')
1247959
def _check_search_kwarg_types(self, kwargs):
        ''''''
        for key in kwargs:
            if key not in self.node_types:
                raise TypeError("Invalid search type: {}".format(key))
171979
def _length_hint(obj):
    """"""
    try:
        return len(obj)
    except (AttributeError, TypeError):
        try:
            get_hint = type(obj).__length_hint__
        except AttributeError:
            return None
        try:
            hint = get_hint(obj)
        except TypeError:
            return None
        if hint is NotImplemented or \
           not isinstance(hint, int_types) or \
           hint < 0:
            return None
        return hint
688489
def CheckInputArgs(*interfaces):
    
    l = len(interfaces)
    def wrapper(func):
        def check_args(self, *args, **kw):
            for i in range(len(args)):
                if (l > i and interfaces[i].providedBy(args[i])) or interfaces[-1].providedBy(args[i]):
                    continue
                if l > i: raise TypeError, 'arg %s does not implement %s' %(args[i], interfaces[i])
                raise TypeError, 'arg %s does not implement %s' %(args[i], interfaces[-1])
            func(self, *args, **kw)
        return check_args
    return wrapper
186023
def _scan(self, type):
        
        tok = self._scanner.token(self._pos, frozenset([type]))
        if tok[2] != type:
            err = SyntaxError("SyntaxError[@ char %s: %s]" % (repr(tok[0]), "Trying to find " + type))
            err.pos = tok[0]
            raise err
        self._pos += 1
        return tok[3]
106174
def _infer_type_impl(self, partial, *args, **kwargs):
        """"""
        # pylint: disable=too-many-locals
        if len(args) != 0 and len(kwargs) != 0:
            raise ValueError('Can only specify known argument \
                    types either by positional or kwargs way.')
        sdata = []
        if len(args) != 0:
            keys = c_array(ctypes.c_char_p, [])
            for s in args:
                if s is not None:
                    s = _numpy.dtype(s).type
                    if s not in _DTYPE_NP_TO_MX:
                        raise TypeError('Argument need to be one of ' + str(_DTYPE_NP_TO_MX))
                    sdata.append(_DTYPE_NP_TO_MX[s])
                else:
                    sdata.append(-1)
        else:
            str_keys = []
            for k, v in kwargs.items():
                v = _numpy.dtype(v).type
                if v in _DTYPE_NP_TO_MX:
                    str_keys.append(k)
                    sdata.append(_DTYPE_NP_TO_MX[v])
            keys = c_str_array(str_keys)
        arg_type_size = mx_uint()
        arg_type_data = ctypes.POINTER(ctypes.c_int)()
        out_type_size = mx_uint()
        out_type_data = ctypes.POINTER(ctypes.c_int)()
        aux_type_size = mx_uint()
        aux_type_data = ctypes.POINTER(ctypes.c_int)()
        complete = ctypes.c_int()
        if partial:
            infer_func = _LIB.MXSymbolInferTypePartial
        else:
            infer_func = _LIB.MXSymbolInferType
        check_call(infer_func(
            self.handle,
            mx_uint(len(sdata)),
            keys,
            c_array_buf(ctypes.c_int, array('i', sdata)),
            ctypes.byref(arg_type_size),
            ctypes.byref(arg_type_data),
            ctypes.byref(out_type_size),
            ctypes.byref(out_type_data),
            ctypes.byref(aux_type_size),
            ctypes.byref(aux_type_data),
            ctypes.byref(complete)))
        if complete.value != 0:
            arg_types = [
                _DTYPE_MX_TO_NP[arg_type_data[i]] for i in range(arg_type_size.value)]
            out_types = [
                _DTYPE_MX_TO_NP[out_type_data[i]] for i in range(out_type_size.value)]
            aux_types = [
                _DTYPE_MX_TO_NP[aux_type_data[i]] for i in range(aux_type_size.value)]
            return (arg_types, out_types, aux_types)
        else:
            return (None, None, None)
111812
def guess_type(s):
    
    sc = s.replace(',', '') # remove comma from potential numbers

    try:
        return int(sc)
    except ValueError:
        pass

    try:
        return float(sc)
    except ValueError:
        pass

    return s
1303866
def check_return(callable_name: str, r: typing.Any,
                 hints: typing.Mapping[str, type]) -> None:
    
    correct = True
    if 'return' not in hints:
        return
    _, correct = check_type(r, hints['return'])
    if not correct:
        raise TypeError(
            'Incorrect return type `{}`, expected {}. for: {}'.format(
                type(r), hints.get('return'), callable_name
            )
        )
88459
def parse_type(defn, preprocess=True):
    
    if pycparser is None:
        raise ImportError("Please install pycparser in order to parse C definitions")

    defn = 'typedef ' + defn.strip('; \n\t\r') + ' QQQQ;'

    if preprocess:
        defn = do_preprocess(defn)

    node = pycparser.c_parser.CParser().parse(make_preamble()[0] + defn)
    if not isinstance(node, pycparser.c_ast.FileAST) or \
            not isinstance(node.ext[-1], pycparser.c_ast.Typedef):
        raise ValueError("Something went horribly wrong using pycparser")

    decl = node.ext[-1].type
    return _decl_to_type(decl)