On 02/09/16 19:04, Steven D'Aprano 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.
Why would that be overly permissive? It infers the most precise type possible.


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

Would you want the checker to infer Union[HTTPServer, float]? I
wouldn't. I would want the checker to complain that the two branches of
the `if` result in different types for x. If I really mean it, then I
can give a type-hint.
Yes, the checker would infer that the type of x (strictly, all uses of x that are defined by these definitions) is Union[HTTPServer, float].

You example is incomplete, what do you do with x?
If you pass x to a function that takes Union[HTTPServer, float] then there is no error.
If you pass it to a function that takes a number then you get an error:
"Cannot use HTTPServer (from line 2) as Number (line ...)"
as one would expect.

When it comes to checkers, people hate false positives. Flagging correct code as erroneous because it is bad 'style' is really unpopular.


In any case, this PEP isn't about specifying when to declare variable
types, it is for picking syntax. Do you have a better idea for variable
syntax?

No. I think that defining the type of variables, rather than expressions is a bad idea.

Cheers,
Mark.
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to