Python Sanity Proposal: Type Hinting Solution

Chris Angelico rosuav at gmail.com
Sat Jan 24 00:38:48 EST 2015


On Sat, Jan 24, 2015 at 4:29 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Sufficiently clever type-checkers may use assertions to infer types, but
> requiring this is a non-starter.

Or they could use the isinstance checks themselves to infer types.

def func(arg):
    if not isinstance(arg, int): raise ValueError("Expected an integer")

It's fairly straight-forward to do an AST parse on a module, iterate
over it for functions, and then look for a specific pattern like the
above:

If(test=UnaryOp(op=Not(), operand=Call(func=Name(id='isinstance',
ctx=Load()), args=[Name(id='arg', ctx=Load()), Name(id='int',
ctx=Load())], keywords=[], starargs=None, kwargs=None)),
body=[Raise(exc=Call(func=Name(id='ValueError', ctx=Load()),
args=[Str(s='Expected an integer')], keywords=[], starargs=None,
kwargs=None), cause=None)], orelse=[])

... okay, that's not exactly pretty, but it's still a straight-forward
structure. But having just watched a PyCon talk about PyPy and RPython
and type inference, it's pretty clear that static analysis can do a
*lot* more than this; so really, looking for isinstance checks is both
too hard and too simplistic to be really worth doing. Type hinting is
a different beast.

ChrisA



More information about the Python-list mailing list