[Python-Dev] PEP 526 ready for review: Syntax for Variable and Attribute Annotations

Guido van Rossum guido at python.org
Thu Sep 1 16:14:59 EDT 2016


On Thu, Sep 1, 2016 at 10:30 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, Aug 30, 2016 at 02:20:26PM -0700, Guido van Rossum wrote:
>
>> - Whether (given PEP 484's relative success) it's worth adding syntax
>> for variable/attribute annotations.
>
> The PEP makes a good case that it does.

Thanks, I agree. :-)

>> - Whether the keyword-free syntax idea proposed here is best:
>>   NAME: TYPE
>>   TARGET: TYPE = VALUE
>
> I think so.
>
> That looks like similar to the syntax used by TypeScript:
>
> http://www.typescriptlang.org/docs/handbook/type-inference.html
>
> let zoo: Animal[] = [new Rhino(), new Elephant(), new Snake()];

And Rust.

In the tracker issue we're still tweaking this, e.g. the latest idea
is that after all we'd like to simplify the syntax to

TARGET: TYPE [= VALUE]

Please read the end of the tracker discussion:
https://github.com/python/typing/issues/258#issuecomment-244188268

> Some additional thoughts:
>
> Is it okay to declare something as both an instance and class attribute?
>
> class X:
>     spam: int
>     spam: ClassVar[Str] = 'suprise!'
>
>     def __init__(self):
>         self.spam = 999
>
>
> I would expect it should be okay.

I think it would be confusing because the class var would be used as
the default if the instance var is not defined.

> It is more common in Python circles to talk about class and instance
> *attributes* than "variables". Class variable might be okay in a
> language like Java where classes themselves aren't first-class values,
> but in Python "class variable" always makes me think it is talking about
> a variable which is a class, just like a string variable or list
> variable. Can we have ClassAttr[] instead of ClassVar[]?

We went back and forth on this. I really don't like to use the word
attribute here, because a method is also an attribute. And instance
variable sounds more natural to me than instance attribute.

Also we now have global variables, class variables, instance
variables, and local variables, all of which can be annotated.

(The PEP's language is actually a bit inconsistent here.)

> Other than that, +1 on the PEP.

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


More information about the Python-Dev mailing list