From 82fbafb1186456f126de503f5514ad8e6a3638b8 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Wed, 10 Aug 2016 15:17:50 -0700 Subject: [PATCH] PEP 0526 -- variable declarations (#70) This PEP is *not* ready for review! This commit is just to claim the PEP number. --- pep-0526.txt | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 pep-0526.txt diff --git a/pep-0526.txt b/pep-0526.txt new file mode 100644 index 000000000..2ea30eab9 --- /dev/null +++ b/pep-0526.txt @@ -0,0 +1,57 @@ +PEP: 526 +Title: Variable Declaration Syntax +Version: $Revision$ +Last-Modified: $Date$ +Author: Ryan Gonzalez , Philip House , Guido van Rossum +Status: Draft +Type: Standards Track +Content-Type: text/x-rst +Created: 09-Aug-2016 +Python-Version: 3.6 + +Abstract +======== + +PEP 484 introduced type hints and; In particular, it introduced the notion of +type comments:: + + # a is specified to be a list of ints. + a = [] # type: List[int] + # b is a string + b = None # type: str + class Cls: + my_class_attr = True # type: bool + +This PEP aims at adding syntax to Python for declaring the types of variables and +attributes, instead of expressing them through comments:: + + a: List[int] = [] + b: str + class Cls: + my_class_attr: ClassAttr[bool] = True + +Rationale +========= + +Although type comments work well, the fact that they're expressed through +comments has some downsides: + +- Text editors often highlight comments differently from type declarations. +- There isn't a way to declare the type of an undefined variable; you need to + initialize it to ``None`` (e.g. ``a = None # type: int``). +- Variables declared in a conditional branch are difficult to read:: + + if some_value: + my_var = function() # type: Logger + else: + my_var = another_function() # Why isn't there a type here? + +- Since type comments aren't actually part of the language, if a Python script + wants to parse them, it would require a custom parser instead of just using + ``ast``. +- It's impossible to retrieve the annotations at runtime outside of attempting to + find the module's source code and parse it at runtime, which is inelegant, to + say the least. + +The majority of these issues can be alleviated by making the syntax a core part of +the language.