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

Guido van Rossum guido at python.org
Tue Aug 2 18:09:19 EDT 2016


On Mon, Aug 1, 2016 at 4:35 PM, Daniel Moisset <dmoisset at machinalis.com> wrote:
> On Mon, Aug 1, 2016 at 10:31 PM, Guido van Rossum <guido at python.org> wrote:
>> 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'd say that if I have a class C with a class variable cv, instance variable
> iv, a good type checking system should detect:
>
> C.cv # ok
> C.iv # error!
> C().iv # ok
>
> which is something that PEP484 doesn't clarify much (and mypy flags all 3 as
> valid)

Yeah, this is all because you can't express that in Python either.
When you see an assignment in a class body you can't tell if it's
meant as an instance variable default or a class variable (except for
some specific cases -- e.g. nested class definitions are pretty
obvious :-).

> So in short, I think it is relevant to specify differently class vs instance
> vars.

Agreed, we need to invent a workable proposal for this. Here's a strawman:

- The default is an instance variable (backed by a class variable as
default if there's an initial value)
- To define a class variable, prefix the type with 'class`

Example:

class C:
    a: int  # instance var
    b: List[int] = None  # instance var
    c: class List[int] = []  # class var

Class variables must come with an initializer; instance variables may
or may not have an initializer. (Bonus: instance variable initializers
must be immutable values.)

Regarding everything involving multiple variables (either `a = b = 0`
or `a, b = 0, 0`) I propose that those cannot be combined with types.
Period.

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


More information about the Python-ideas mailing list