[Python-ideas] Trial balloon: adding variable type declarations in support of PEP 484
Joao S. O. Bueno
jsbueno at python.org.br
Wed Aug 3 11:31:15 EDT 2016
I may have missed that on the message deluge so far - but would the
type annotations
be available at runtime, like parameter annotations live in "__annotations__"?
An __annotations__ dict straight in the class itself? I thinkt hat is
the obvious thing - although I did not see it in the above messages.
(A s I said, I may have missed its mention)
That is ratehr important because then, beyond enabling static code
analysis it is easy to have third party frameworks that enforce typing
in runtime.
On 3 August 2016 at 12:13, Joao S. O. Bueno <jsbueno at python.org.br> wrote:
> On 3 August 2016 at 11:51, Daniel Moisset <dmoisset at machinalis.com> wrote:
>> May be I've gotten wrong my python style for many years, but I always
>> considered that the "proper" way to create instance variables was inside the
>> initializer (or in rare occasions, some other method/classmethod). For me,
>> an assignment at a class body is a class variable/constant.
>>
>> So I was going to propose "type declarations at class level are always for
>> class variables, and inside methods (preceded by "self.") are for instance
>> variables". Using class level variables for defaults always seemed
>> unpythonic and error prone (when mutable state is involved) to me. I felt
>> that was common practice but can't find documentation to support it, so I'd
>> like to hear if I'm wrong there :)
>
> You've just missed one of the most powerful side-effects of how
> Python's class and instance variables interact:
>
> class Spaceship:
> color = RED
> hitpoints = 50
>
> def powerup(self):
>
> self.color = BLUE
> self.hitpoints += 100
>
> Above: the defaults are good for almost all spaceship instaces - but
> when one of them is "powered up", and only them, that instance values
> are defined to be different than the defaults specified in the class.
> At that point proper instance variables are created in the instanceś
> __dict__, but for all other instances, the defaults, living in the
> instance's".__class__.__dict__" are just good enough.
More information about the Python-ideas
mailing list