PEP 526 - var annotations and the spirit of python

Bart bc at freeuk.com
Wed Jul 4 14:57:12 EDT 2018


On 04/07/2018 16:31, Steven D'Aprano wrote:
> On Wed, 04 Jul 2018 13:48:26 +0100, Bart wrote:

> Of course the type (whether inferred or annotated) applies for the entire
> scope of that variable.
> 

In that case I don't understand what you're complaining about. You say 
that hinting is not needed here:

   x = 3

because you know x will be int at this point. But what you don't know if 
whether x will keep its int type.

> With type-inference, the type-checker is smart enough to recognise what
> type a variable is supposed to be (at least sometimes):
> 
>      x = 3;  # of course it's an int, what else could it be?
>      x = f(x);
> 
> and likewise complain if f(x) returns something other than an int.

Are you still talking about Python here? Python is famous for being 
highly dynamic. So that that second assignment could set x to ANYTHING.

I though the point of the type hint was to say that x has a particular 
type and it always keeps that same type. That way it is possible to make 
some assumptions about it. Otherwise, what's the point?

I understand that type hinting doesn't enforce anything, such as 
checking that anything assigned to x is actually an int. Although that 
wouldn't be hard to do: just implement every x = y as x = int(y) or 
better, x = intcheck(y).

> There's no point in type checking if you don't, you know, actually
> *check* the types.

> With type inference, the only reason to declare a variable's type is if
> the type checker can't infer it from the code, or if it infers the wrong
> type. (More on this later.)

In Python, the reason to declare a variable's is presumably also to say 
that it HAS a fixed type.

Type inference can still be used for certain purposes, such as 
optimising code, but it's not of much benefit to someone reading the 
code as the results of such analysis won't appear in the source.

-- 
bart


More information about the Python-list mailing list