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

Guido van Rossum guido at python.org
Thu Aug 4 16:32:15 EDT 2016


On Thu, Aug 4, 2016 at 12:11 PM, Daniel Moisset <dmoisset at machinalis.com> wrote:
[...]
> I follow the example perfectly. Now suppose a reader finds the following
> piece of code:
>
> class Starship:
>     stats: class Dict[str, int] = {}  # Pure class variable
>     damage: class int = 0  # Hybrid class/instance variable
>     captain: str  # Pure instance variable
>     speed: float = 0
>
> I added a new attribute (similar to b in your original example). Given that
> the type declaration doesn't say "class",the reader might be inclined to
> think it's an instance variable. But in runtime (if I got you right), that
> variable will be stored in "Starship.__dict__" and writing "Starship.speed =
> 3" will change the speed of those starship instances that still haven't set
> the attribute. So in the end both "damage" and "speed" have "class variable"
> runtime semantics, even when one is flagged as "class" and the other isn't.

We may have to debate more what the checker should allow here. (Since
it's okay for a type checker to disallow things that might actually
work at runtime.) I'm inclined to allow it, as long as the value
assigned to Starship.speed is compatible with float.

> The other combination that feels a bit confusing when adding "class" tags is
> saying "attr: class T", without an initializer.... in what case would
> someone do that? what does it mean if I find some code saying that about the
> class, that it might get that attribute set somewhere else?

Agreed that looks silly. We probably should make that a syntax error.

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


More information about the Python-ideas mailing list