[Python-ideas] Trial balloon: adding variable type declarations in support of PEP 484
Steven D'Aprano
steve at pearwood.info
Mon Aug 1 22:55:09 EDT 2016
On Mon, Aug 01, 2016 at 02:31:16PM -0700, Guido van Rossum 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
Those examples look reasonable to me.
[...]
> 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?
I would think so. Consider the case that you have Class.spam and
Class().spam which may not be the same type. E.g. the class attribute
(representing the default value used by all instances) might be a
mandatory int, while the instance attribute might be Optional[int].
> 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, ''
Require parens around the name:hint.
(a:int), (b:str) = 0, ''
Or just stick to a type hinting comment :-)
What about this case?
spam, eggs = [1, 2.0, 'foo'], (1, '')
[a, b, c], [d, e] = spam, eggs
That becomes:
[(a:int), (b:float), (c:str)], [(x:int), (y:str)] = spam, eggs
which is bearable, but just unpleasant enough to discourage people from
doing it unless they really need to.
--
Steve
More information about the Python-ideas
mailing list