[Python-ideas] ideas for type hints for variable: beyond comments

Chris Angelico rosuav at gmail.com
Tue Sep 1 13:19:29 CEST 2015

On Tue, Sep 1, 2015 at 8:24 PM, Ian <ian.team.python at gmail.com> wrote:
> mypy currently inspects the comment on the line of first assignment for the
> variables to be type hinted.
> It is logical that at some time python language will add support to allow
> these type hints to move from comments to the code as has happened for 'def'
> signatures.

Potential problem: Function annotations are supported all the way back
to Python 3.0, but any new syntax would be 3.6+ only. That's going to
severely limit its value for quite some time. That doesn't mean new
syntax can't be added (otherwise none ever would), but the bar is that
much higher - you'll need an extremely compelling justification.

> The other question is 'what about globals and nonlocals?'.  Currently
> globals and nonlocals need a 'global' or 'nonlocal' statement to allow
> assignment, but what if these values are not assigned in scope?

Not sure what you're talking about here. If they're not assigned in
this scope, then presumably they have the same value they had from
some other scope. You shouldn't need to declare that "len" is a
function, inside every function that calls it. Any type hints should
go where it's assigned, and nowhere else.

> What if we allowed
> global i:int
> or
> nonlocal i:int
> and even
> local i:int
> Permitting a new keyword 'local' to me might bring far more symmetry between
> different cases.

Hey, if you want C, you know where to find it :)

> Use of the 'local' keyword in the global namespace could indicate a value
> not accessible in other namespaces.

I'm not sure what "not accessible" would mean. If someone imports your
module, s/he gains access to all your globals. Do you mean that it's
"not intended for external access" (normally notated with a single
leading underscore)? Or is this a new feature - some way of preventing
other modules from using these? That might be useful, but that's a
completely separate proposal.

> Personally I would like to go even further and allow some syntax to allow
> (or disable) flagging the use of new variables without type hinting as
> possible typos

If you're serious about wanting all your variables to be declared,
then I think you want a language other than Python. There are such
languages around (and maybe even compiling to Python byte-code, I'm
not sure), but Python isn't built that way. Type hinting is NOT
variable declaration, and never will be. (Though that's famous last
words, I know, and I'm not the BDFL or even anywhere close to that. If
someone pulls up this email in ten years and laughs in my face, so be
it. It'd not be the first time I've been utterly confidently wrong!)


More information about the Python-ideas mailing list