Check if a model is of the right type. Raise error if not.

    Parameters
    ----------
    model: model
        Any scikit-learn model

    expected_type: Type
        Expected type of the scikit-learn.
770046
def check_expected_type(model, expected_type):
    
    if (model.__class__.__name__ != expected_type.__name__):
        raise TypeError("Expected model of type '%s' (got %s)" % \
                (expected_type.__name__, model.__class__.__name__))
294348
def validate_type(value, types, **kwargs):
    
    if not is_value_of_any_type(value, types):
        raise ValidationError(MESSAGES['type']['invalid'].format(
            repr(value), get_type_for_value(value), types,
        ))
471545
def check_type(node,expected_type,label,accept_nil = false)
              
        valid_type = true;
        if(@types.has_key?(expected_type))
          valid_type = match_node(node,@types[expected_type],label)
        elsif node.class.to_s != expected_type && !(node.kind_of?(NilClass) && (expected_type=='empty' || accept_nil))
          valid_type = false
        end
       
        return valid_type
        
      end
389881
def _model_sanity(model):
        
        if not isinstance(model, ODEModel) and not isinstance(model, BaseNumericalModel):
            # Such a model should probably not contain derivatives
            for var, expr in model.items():
                if isinstance(var, sympy.Derivative) or expr.has(sympy.Derivative):
                    warnings.warn(RuntimeWarning(
                        'The model contains derivatives in its definition. '
                        'Are you sure you don\'t mean to use `symfit.ODEModel`?'
                    ))
897312
def make_kind_check(python_types, numpy_kind):
    
    def check(value):
        if hasattr(value, 'dtype'):
            return value.dtype.kind == numpy_kind
        return isinstance(value, python_types)
    return check
1152648
def _get_future_expected_model(self, core_element):
        """"""
        for model in self.expected_future_models:
            if model.core_element is core_element:
                # print("expected_future_model found -> remove model:", model, [model], id(model))
                self.expected_future_models.remove(model)
                return model
        return None
1373579
def right_model_factory(*, validator=validators.is_right_model,
                        ld_type='Right', **kwargs):
    
    return _model_factory(validator=validator, ld_type=ld_type, **kwargs)
1064019
def _get_model_instance(model_cls, data):
        
        if not isinstance(data, (model_cls, dict)):
            raise TypeError('{0} is not valid type, instance of '
                            '{1} or dict required'.format(data, model_cls))
        return model_cls(**data) if isinstance(data, dict) else data
883640
def _helper_for_model(self, model_type):
        
        if model_type is models.containers.Container:
            return self.containers
        if model_type is models.images.Image:
            return self.images
        if model_type is models.networks.Network:
            return self.networks
        if model_type is models.volumes.Volume:
            return self.volumes

        raise ValueError('Unknown model type {}'.format(model_type))
348369
private void checkFieldType(int field, Type... expected)
    {
        Type actual = getType(field);
        for (Type type : expected) {
            if (actual.equals(type)) {
                return;
            }
        }

        throw new IllegalArgumentException(format("Expected field %s to be a type of %s but is %s", field, StringUtils.join(expected, ","), actual));
    }
1301057
def check_type(*args, **kwargs):
    ''' 
    '''
    args = tuple(x if isinstance(x, collections.Iterable) else (x,) for x in args)
    kwargs = {x: kwargs[x] if isinstance(kwargs[x], collections.Iterable) else (kwargs[x],) for x in kwargs}

    def decorate(func):
        types = args
        kwtypes = kwargs
        gi = "Got <{}> instead"
        errmsg1 = "to be of type <{}>. " + gi
        errmsg2 = "to be one of type ({}). " + gi
        errar = "{}:{} expected '{}' "
        errkw = "{}:{} expected {} "

        def check(*ar, **kw):
            line = inspect.getouterframes(inspect.currentframe())[1][2]
            fname = os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1])

            for arg, type_ in zip(ar, types):
                if type(arg) not in type_:
                    if len(type_) == 1:
                        raise TypeError((errar + errmsg1).format(fname, line, arg, type_[0].__name__,
                                                                 type(arg).__name__))
                    else:
                        raise TypeError((errar + errmsg2).format(fname, line, arg,
                                                                 ', '.join('<%s>' % x.__name__ for x in type_),
                                                                 type(arg).__name__))
            for kwarg in kw:
                if kwtypes.get(kwarg, None) is None:
                    continue
                if type(kw[kwarg]) not in kwtypes[kwarg]:
                    if len(kwtypes[kwarg]) == 1:
                        raise TypeError((errkw + errmsg1).format(fname, line, kwarg, kwtypes[kwarg][0].__name__,
                                                                 type(kw[kwarg]).__name__))
                    else:
                        raise TypeError((errkw + errmsg2).format(
                            fname,
                            line,
                            kwarg,
                            ', '.join('<%s>' % x.__name__ for x in kwtypes[kwarg]),
                            type(kw[kwarg]).__name__)
                        )

            return func(*ar, **kw)

        return check

    return decorate
1240486
def lookup_model_by_kind(kind):
    
    model = _known_models.get(kind)
    if model is None:
        raise RuntimeError(f"Model for kind {kind!r} not found.")
    return model
65260
def AssertType(value, expected_type):
  
  if not isinstance(value, expected_type):
    message = "Expected type `%r`, but got value `%r` of type `%s`"
    message %= (expected_type, value, type(value))
    raise TypeError(message)
83368
private static void checkFeatureType(Feature feature, String expectedType)
      throws AnalysisEngineProcessException {
    if (!feature.getRange().getName().equals(expectedType)) {
      throw new OpenNlpAnnotatorProcessException(
          ExceptionMessages.WRONG_FEATURE_TYPE,
          new Object[] {feature.getName(),
              expectedType
          });
    }
  }
1250140
def validate_model(  # noqa: C901 (ignore complexity)
    model: Union[BaseModel, Type[BaseModel]], input_data: 'DictStrAny', raise_exc: bool = True, cls: 'ModelOrDc' = None
) -> Union['DictStrAny', Tuple['DictStrAny', Optional[ValidationError]]]:
    
    values = {}
    errors = []
    names_used = set()
    config = model.__config__
    check_extra = config.extra is not Extra.ignore

    for name, field in model.__fields__.items():
        if type(field.type_) == ForwardRef:
            raise ConfigError(
                f'field "{field.name}" not yet prepared so type is still a ForwardRef, '
                f'you might need to call {model.__class__.__name__}.update_forward_refs().'
            )

        value = input_data.get(field.alias, _missing)
        using_name = False
        if value is _missing and config.allow_population_by_alias and field.alt_alias:
            value = input_data.get(field.name, _missing)
            using_name = True

        if value is _missing:
            if field.required:
                errors.append(ErrorWrapper(MissingError(), loc=field.alias, config=model.__config__))
                continue
            value = deepcopy(field.default)
            if not model.__config__.validate_all and not field.validate_always:
                values[name] = value
                continue
        elif check_extra:
            names_used.add(field.name if using_name else field.alias)

        v_, errors_ = field.validate(value, values, loc=field.alias, cls=cls or model.__class__)  # type: ignore
        if isinstance(errors_, ErrorWrapper):
            errors.append(errors_)
        elif isinstance(errors_, list):
            errors.extend(errors_)
        else:
            values[name] = v_

    if check_extra:
        extra = input_data.keys() - names_used
        if extra:
            if config.extra is Extra.allow:
                for f in extra:
                    values[f] = input_data[f]
            else:
                for f in sorted(extra):
                    errors.append(ErrorWrapper(ExtraError(), loc=f, config=config))

    if not raise_exc:
        return values, ValidationError(errors) if errors else None

    if errors:
        raise ValidationError(errors)
    return values
615796
def smart_content_type_for_model(model):
    
    try:
        # noinspection PyPackageRequirements,PyUnresolvedReferences
        from django.contrib.contenttypes.models import ContentType
    except ImportError:
        print("Django is required but cannot be imported.")
        raise

    if model._meta.proxy:
        return ContentType.objects.get(app_label=model._meta.app_label,
                                       model=model._meta.object_name.lower())
    else:
        return ContentType.objects.get_for_model(model)
5259
def validate(self, error_message=None):
        

        if self.is_type():
            return

        if not error_message:
            error_message = "invalid value type"

        raise TypeError(
            "{}: expected={}, actual={}".format(error_message, self.typename, type(self._data))
        )