Add `arg_check_type()` to `types`

Which is useful when checking if the type of an argument is correct.
The internal implementation may like this:

def arg_check_type(expected_type:type, instance:object, arg_name:str):
    if not isinstance(instance, expected_type):
        raise TypeError(
            f"Argument '{arg_name}' must be {expected_type.__name__}, got {instance.__class__.__name__}."
        )

Example:

def func(arg:int):
    types.arg_check_type(int, arg, "arg")
    return arg.to_bytes(10, "big")

func("hello")

# TypeError: Argument 'arg' must be int, got str.

There are decorators that do this for all of the arguments.

Do you insist this is checked at runtime? Or is compile/type-checking time sufficient?
in the latter case, typing.assert_type(val, typ, /) may serve your needs.

1 Like

Thanks, that’s what I want.