Why has __new__ been implemented as a static method?

Jurko Gospodnetić jurko.gospodnetic at pke.hr
Sat May 3 06:37:24 EDT 2014


   Hi all.

   I was wandering why Python implements its __new__ method as a static 
and not a class method?

   __new__ always accepts a cls parameter, which lead me to believe it 
was a class method. Also, implementing __new__ as a class method seems 
natural when thinking about __new__ as 'a method you call on a class to 
create a new instance of that class'.

   The difference between the two implementations is admittedly not that 
significant. In most cases __new__ would still need to have its cls 
parameter explicitly specified since it is most often called on a class 
and not on an instance.

   Having it implemented as a class method would allow this:

     class X:
       def __new__(cls, x):
         return super().__new__(x)

   instead of having to do this, as we do now:

     class X:
       def __new__(cls, x):
         return super().__new__(cls, x)


   Thinking about this some more - I guess having it as a static method 
allows you to use super() and still create a new 'subclass' when asked 
to instantiate a base class. Perhaps some sort of a factory pattern 
implementation like so:

     class Base:
       def __new__(cls, x):
         actual_class = get_class_for(x)
         return super().__new__(actual_class, x)

   If __new__ were a class method, the same logic could not be so easily 
implemented as you would need to call __new__ on actual_class, and so 
each actual_class would need to implement its own __new__ skipping its 
direct parent's __new__ - yuck... what a mess...

   Could that be the actual use case causing Guido to model __new__ as a 
static method? Or was it something else?


   I'm not suggesting this be changed, of course. I'm just curious as to 
whether I'm not fully understanding something in this part of Python. I 
generally find Python highly intuitive and it's not often something 
about it takes me by surprise like this. :-)

   Thanks in advance.

   Best regards,
     Jurko Gospodnetić

P.S.
   Normally, I'd chalk this issue up under 'bike-shedding', but it came 
up while teaching others about Python and so does not feel right leaving 
it as 'because that's the way it is'. :-)




More information about the Python-list mailing list