[Python-Dev] What should a good type checker do? (was: Please reject or postpone PEP 526)

Koos Zevenhoven k7hoven at gmail.com
Fri Sep 2 18:49:00 EDT 2016


On Fri, Sep 2, 2016 at 9:04 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, Sep 02, 2016 at 08:10:24PM +0300, Koos Zevenhoven wrote:
>
>> A good checker should be able to infer that x is a union type at the
>> point that it's passed to spam, even without the type annotation. For
>> example:
>>
>> def eggs(cond:bool):
>>     if cond:
>>         x = 1
>>     else:
>>         x = 1.5
>>     spam(x)   # a good type checker infers that x is of type Union[int, float]
>
> Oh I really hope not. I wouldn't call that a *good* type checker. I
> would call that a type checker that is overly permissive.

I guess it's perfectly fine if we disagree about type checking ideals,
and I can imagine the justification for you thinking that way. There
can also be different type checkers, and which can have different
modes.

But assume (a) that the above function is perfectly working code, and
spam(...) accepts Union[int, float]. Why would I want the type checker
to complain?

Then again, (b) instead of that being working code, it might be an
error and spam only takes float. No problem, the type checker will
catch that.

In case of (b), to get the behavior you want (but in my hypothetical
semantics), this could be annotated as

def eggs(cond:bool):
    x : float
    if cond:
        x = 1  # type checker says error
    else:
        x = 1.5
    spam(x)

So here the programmer thinks the type of x should be more constrained
than what spam(...) accepts.

Or you might have something like this

def eggs(cond:bool):
    if cond:
        x = 1
    else:
        x = 1.5
    # type checker has inferred x to be Union[int, float]
    x : float  # type checker finds an error
    spam(x)

Here, the same error is found, but at a different location.

> Maybe you think that it's okay because ints and floats are somewhat
> compatible. But suppose I wrote:
>
>     if cond:
>         x = HTTPServer(*args)
>     else:
>         x = 1.5

It might be clear by now, but no, that's not why I wrote that. That
was just a slightly more "realistic" example than this HTTP & 1.5 one.

[...]
> Do you have a better idea for variable
> syntax?

I had one but it turned out it was worse.

-- Koos

>
>
> --
> Steve
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: https://mail.python.org/mailman/options/python-dev/k7hoven%40gmail.com



-- 
+ Koos Zevenhoven + http://twitter.com/k7hoven +


More information about the Python-Dev mailing list