PEP 526 - var annotations and the spirit of python
bc at freeuk.com
Wed Jul 4 08:48:26 EDT 2018
On 04/07/2018 06:52, Steven D'Aprano wrote:
> On Sun, 01 Jul 2018 17:22:43 -0500, Tim Daneliuk wrote:
>>> x: int = 3
>> This strikes me as syntactic noise. Python is dynamically typed and
>> will remain so. Why clutter the language - even optionally - with stuff
>> like this?
> There's no need to declare x:int = 3 since any linter worth its salt
> ought to be able to infer that x is an int if it is assigned the value 3.
> Anyone writing that needs to be slapped with a clue-stick, it's not 1971
> any more, type inference ought to be considered bare minimum for even a
> halfway decent type checker or linter.
Presumably one type hint applies for the whole scope of the variable,
not just the one assignment. Which means that here:
x: int = 3
x = f(x)
you know x should still an int after these two statements, because the
type hint says so. Without it:
x = 3
x = f(x)
x could be anything.
> A better example would be:
> x: int = None
> which ought to be read as "x is an int, or None, and it's currently None".
In that case the type hint is lying. If both x and y have type hints of
'int', then with this:
z = x + y
you might infer that z will be also 'int' (whether it it type hinted or
not). But if either of x and y can be None, then this might not even
If something is an int, then make it an int:
x: int = 0
More information about the Python-list