[Python-ideas] Semantics for type checking (was: What should a good type checker do?)

Chris Angelico rosuav at gmail.com
Sat Sep 3 19:22:06 EDT 2016


On Sun, Sep 4, 2016 at 7:44 AM, Koos Zevenhoven <k7hoven at gmail.com> wrote:
>> I wonder if it would be different if you wrote that as a single expression:
>>
>> x = 1 if cond else 1.5
>>
>> x = sum([1] + [0.5] * cond)
>>
>> What should type inference decide x is in these cases? Assume an
>> arbitrarily smart type checker that can implement your ideal; it's
>> equally plausible to pretend that the type checker can recognize an
>> if/else block (or even if/elif/else tree of arbitrary length) as a
>> single "assignment" operation. IMO both of these examples - and by
>> extension, the if/else of the original - should be assigning a Union
>> type.
>
> In the first case it would indeed again be Union[int, float] (the code
> is basically equivalent after all).
>
> In the second case, the checker would infer List[Union[int, float]].
> No magic involved, assuming that list.__add__ is annotated precisely
> enough.

I think you missed the sum() call there. Most likely, the sum of
List[Union[anything]] would be Union[anything], so these would all be
the same (which was my original point).

ChrisA


More information about the Python-ideas mailing list