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

Guido van Rossum guido at python.org
Mon Aug 1 17:31:16 EDT 2016


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. :-)

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

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?

Third, there's an annoying thing with tuples/commas here. On the one
hand, in a function declaration, we may see (a: int = 0, b: str = '').
On the other hand, in an assignment, we may see

a, b = 0, ''

Suppose we wanted to add types to the latter. Would we write this as

a, b: int, str = 0, ''

or as

a: int, b: str = 0, ''

??? Personally I think neither is acceptable, and we should just write it as

a: int = 0
b: str = ''

but this is a slight step back from

a, b = 0, ''   # type: (int, str)

-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-ideas mailing list