[Python-ideas] Add an option that allow check Type Hints in runtime

Chris Angelico rosuav at gmail.com
Fri Jul 8 04:30:52 EDT 2016


On Fri, Jul 8, 2016 at 6:19 PM, Ma Lin <animalize81 at hotmail.com> wrote:
> I mean real check by the interpreter, not an '__annotations__' attribute.
> And I just had a look, mypy is a static checker, without actually running
> the code.
>
> My thought is modifying CALL_FUNCTION and RETURN_VALUE of the interpreter,
> so that allow them to check in each function calling when option enalbed.
>
> Cite a case:
>
> def fun(a: str, b: int) -> int:
>     return len(a) + b
> fun('arg1', 'arg2')
>
> Whit the option and run this code, the interpreter will give an error
> prompt:
>     Type of argument b is wrong. (or something like this)
>
> This is very useful for development and debugging.

You should still be able to do it without changing the core interpreter.

def enforce_types(func):
    @functools.wraps(func)
    def wrapped(*args, **kw):
        if not args_valid(args, kw, func.__annotations__):
            raise TypeError
        ret = func(*args, **kw)
        if not type_valid(ret, func.__annotations__["return"]):
            raise TypeError
    return wrapped

@enforce_types
def fun(a: str, b: int) -> int:
    return len(a) + b

fun('arg1', 'arg2')


Now all you have to do is write the type_valid function (takes an
object and an annotation, returns True if it matches) and args_valid
(takes the positional and keyword args, pairs them up against the
function's params, and returns True if all(type_valid(...)) for the
args). The only benefit of hacking the interpreter core for this is
that you'd save the hassle of pairing up positional/keyword args
against the parameters.

ChrisA


More information about the Python-ideas mailing list