[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:13:21 EDT 2016


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