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

Nick Coghlan ncoghlan at gmail.com
Sat Aug 6 04:09:39 EDT 2016


On 6 August 2016 at 02:12, Guido van Rossum <guido at python.org> wrote:
> On Fri, Aug 5, 2016 at 12:40 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> That is:
>>
>>     class Starship:
>>         stats class: Dict[str, int] = {}  # Pure class variable
>>         damage class: int = 0  # Hybrid class/instance variable
>>         captain: str  # Pure instance variable
>>
>> Pronounced as:
>>
>>     "stats is declared on the class as a dict mapping from strings to
>> integers and is initialised as an empty dict"
>>     "damage is declared on the class as an integer and is initialised as zero"
>>     "captain is declared on instances as an integer"
>>
>> Just a minor thing, but the closer association with the name reads
>> better to me since "Class attribute or instance attribute?" is really
>> a property of the name binding, rather than of the permitted types
>> that can be bound to that name
>
> Hmm... But the type is *also* a property of the name binding. And I
> think the "class-var-ness" needs to be preserved in the
> __annotations__ dict somehow, so that's another reason why it
> "belongs" to the type rather than to the name binding (a nebulous
> concept to begin with).
>
> Also, I like the idea that everything between the ':' and the '=' (or
> the end of the line) belongs to the type checker. I expect that'll be
> easier for people who aren't interested in the type checker.

Fair point, although this and the __var_annotations__ discussion also
raises the point that annotations have to date always been valid
Python expressions. So perhaps rather than using the class keyword, it
would make sense to riff off classmethod and generic types to propose:

    class Starship:
        stats: ClassAttr[Dict[str, int]] = {}  # Pure class variable
        damage: DefaultAttr[int] = 0  # Hybrid class/instance variable
        captain: str  # Pure instance variable

Pronounced as:

    "stats is a class attribute mapping from strings to integers and
is initialised as an empty dict"
    "damage is an instance attribute declared as an integer with a
default value of zero defined on the class"
    "captain is an instance attribute declared as a string"

In addition to clearly distinguishing class-only attributes from
class-attribute-as-default-value, this would also mean that the
specific meaning of those annotations could be documented in
typing.ClassAttr and typing.DefaultAttr, rather than needing to be
covered in the documentation of the type annotation syntax itself.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list