Skip to content

type_check

is_roughly_correct_type(obj, type_)

Check if obj is roughly correct type.

The roughly correct type means that the first element of the sequence and mapping only checked.

Parameters:

Name Type Description Default
obj Any

target object

required
type_ Any

target type

required

Returns:

Name Type Description
bool bool

True if obj is roughly correct type, otherwise False

Source code in jijmodeling_transpiler/utils/type_check.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def is_roughly_correct_type(obj: typ.Any, type_: typ.Any) -> bool:
    """Check if obj is roughly correct type.

    The roughly correct type means that the first element of the sequence and mapping only checked.

    Args:
        obj (Any): target object
        type_ (Any): target type

    Returns:
        bool: True if obj is roughly correct type, otherwise False
    """

    origin_type = typ.get_origin(type_)

    if origin_type is typ.Union:
        union_types = typ.get_args(type_)
        return any(
            is_roughly_correct_type(obj, union_type) for union_type in union_types
        )

    if origin_type is None:
        origin_type = type_
    if not isinstance(obj, origin_type):
        return False

    if isinstance(obj, Mapping):
        if len(obj) == 0:
            return True
        value = next(iter(obj.values()))
        key_type, value_type = typ.get_args(type_)

        value_check = is_roughly_correct_type(value, value_type)
        key_check = is_roughly_correct_type(next(iter(obj.keys())), key_type)
        return value_check and key_check

    if isinstance(obj, Sequence) and not isinstance(obj, str):
        if not obj:
            return True

        item_type = typ.get_args(type_)
        return is_roughly_correct_type(obj[0], item_type)

    return True

raise_type_error(var_name, obj, type_)

Raise TypeError.

Parameters:

Name Type Description Default
obj Any

target object

required
type_ Any

target type

required
Source code in jijmodeling_transpiler/utils/type_check.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def raise_type_error(var_name: str, obj: typ.Any, type_: typ.Any) -> None:
    """Raise TypeError.

    Args:
        obj (Any): target object
        type_ (Any): target type
    """
    if is_roughly_correct_type(obj, type_):
        return
    raise TypeError(
        f"Type of `{var_name}` is {_type_name(obj)}, but {type_} is expected."
    )