[Python-ideas] Enabling / disabling optional type hinting

Gregory P. Smith greg at krypto.org
Sat Mar 23 13:37:43 EDT 2019


On Sat, Mar 23, 2019 at 7:37 AM Andre Roberge <andre.roberge at gmail.com>
wrote:

> Consider the following example [1]:
>
>  Python 3.7.0 (v3.7.0:1bf9cc5093...
>  >>> d = {
>  ...   "injury": "flesh wound"
>  ... }
>  >>> d["answer"]: 42
>  >>> if "answer" in d:
>  ...     print("Don't panic!")
>  ... else:
>  ...     print("Sorry, I can't help you.")
>  ...
>  Sorry, I can't help you.
>
> = =
> No SyntaxError raised (which would have been the case before version 3.5?)
> and yet what could be a very unexpected result occurred.
>
> Of course, the problem is with the line
>
> d["answer"]: 42
>
> which is not an assignment but is an "optional" type hint.
>

A useless statement like that isn't likely to be typed.  I've never seen
anyone do that.

Sure, someone is going to typo and omit the = from a := assignment in 3.8
but the walrus is unlikely to be used outside of an conditional or loop
test context so this seems like a made up problem.  (if anything, this
possibility encourages people not to use the walrus in unintended places).
Someone might also typo it by meaning to use a ; for multiple statements
but enter : instead.  Again, very rare.  Because ; is frowned upon.

A linter (running live as part of an editor/ide these days) can flag most
meaningless annotations quite easily.

I think it would be very useful to have a way to turn off completely type
> hinting and flag any use of code like the above as a SyntaxError.
>
> My preference would be if type hinting would be something that is enabled
> per file with a top-level comment pragma, something like
>
> # type: enable
>
> Failing that, having a to-level comment pragma like
>
> # type: disable
>

Too late.  Requiring something like that would break existing code.

might be acceptable as it would not require any change to any existing
> file. However, the other option would be more inline with type hinting
> being "optional" and something that should not trip beginners who are not
> aware of its existence.
>

What evidence is there that this frequently trips up beginners?

Enhancing the dev environments beginners use to automatically lint would be
better and would automate some learning, handling cases way beyond this one.

-gps
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190323/bb7b1580/attachment.html>


More information about the Python-ideas mailing list