[Python-ideas] Trial balloon: adding variable type declarations in support of PEP 484

Eric Snow ericsnowcurrently at gmail.com
Mon Aug 1 18:40:43 EDT 2016


On Mon, Aug 1, 2016 at 3:31 PM, Guido van Rossum <guido at python.org> wrote:
> PEP 484 doesn't change Python's syntax. Therefore it has no good
> syntax to offer for declaring the type of variables, and instead you
> have to write e.g.
>
> a = 0  # type: float
> b = []  # type: List[int]
> c = None  # type: Optional[str]
>
> I'd like to address this in the future, and I think the most elegant
> syntax would be to let you write these as follows:
>
> a: float = 0
> b: List[int] = []
> c: Optional[str] = None
>
> (I've considered a 'var' keyword in the past, but there just are too
> many variables named 'var' in my code. :-)

As noted by someone else, what about "local":

local a: float

It seems like nonlocal and global would need the same treatment:

nonlocal b: List[int]
global c: Optional[str]

>
> There are some corner cases to consider. First, to declare a
> variable's type without giving it an initial value, we can write this:
>
> a: float

Isn't that currently a NameError?  Is it worth making this work while
preserving the error case?  A "local" keyword would solve the problem,
no?

>
> Second, when these occur in a class body, they can define either class
> variables or instance variables. Do we need to be able to specify
> which?

In the immediate case I'd expect the former.  We don't currently have
a canonical way to "declare" instance attributes in the class
definition.  It may be worth sorting that out separately and
addressing the PEP 484 aspect at that point.

>
> Third, there's an annoying thing with tuples/commas here.

What about unpacking into explicit displays?  For example:

(a, b) = 0, ''
[a, b] = 0, ''

-eric


More information about the Python-ideas mailing list