[Python-ideas] Typecheckers: there can be only one
Steven D'Aprano
steve at pearwood.info
Thu Sep 8 14:08:45 EDT 2016
On Thu, Sep 08, 2016 at 07:46:41PM +1000, Hugh Fisher wrote:
> The interpreter certainly thinks they're code rather than comments or
> docstrings, even before PEP 526. I type this into my Python 3.4
> interpreter:
>
> >>> def foo(x:itn):
> >>> ... return x
>
> and the interpreter raises a NameError because 'itn' is not defined.
Right. Python has supported annotations since 3.0. Folks have been able
to confuse themselves by "declaring" (annotating) the types of function
parameters for almost a decade, and yet your fears of newbies being
confused by the lack of type checks by default has not eventuated.
But I'll grant you that you are partially right: I completely expect
that some people will (through inexperience or ignorance) write
x: dict = 1
and be surprised that Python doesn't flag it as an error. That's a
matter for education. Beginners to Python are confused by many things,
such as the (non)fact that "ints are passed by value and lists by
reference".
I daresay that some people will point to this as a Python "WAT?" moment,
just as they already point to the fact that Python doesn't flag
x = 1 + "foo"
as an error until runtime as a WAT moment.
Okay, fine. It is kinda funny that the Python compiler can't tell that
numbers and strings can't be added together even when they are literals.
Currently we can write:
x = 1
assert isinstance(x, dict)
and the interpreter will allow it. The only difference is that
assertions are on by default and annotations are off by default. (To be
clear: annotations will set the special __annotations__ variable, but by
default the annotation is note checked for correctness.)
Assertions can be used as checked comments in Python, and annotations
can be seen as similar: they are *checked type comments* for third-party
tools. And, just maybe, Python 5000 or thereabouts will mandate that
every Python interpreter include a built-in type checker capable of at
least flagging errors like `x: dict = 1`.
But it will be off by default.
> Annotations look like code, they're mixed in with names and operators
> and literals and keywords, and all the standard syntax and semantic
> checks are applied.
I agree -- annotations are code.
--
Steve
More information about the Python-ideas
mailing list