[Tutor] use of __new__

Steven D'Aprano steve at pearwood.info
Fri Mar 12 12:56:37 CET 2010


I've taken the liberty of replying back to the list rather than in 
private. Denis, if you mean to deliberately reply privately, please say 
so at the start of the email, otherwise I will assume it was an 
accident.


On Fri, 12 Mar 2010 09:56:11 pm spir wrote:

> Side-question: Why use super() when we know it can only be unicode?

super is necessary for multiple inheritance to work correctly:

class SpecialString(MyOtherStringClass, Unicode):
    ...

will have hard-to-find bugs if you don't use super. But if you are 
absolutely sure that you will never directly or indirectly use multiple 
inheritance, then you could replace the calls to super with:

unicode.__new__(...)

But why bother? super does the right thing for both single and multiple 
inheritance.


> And why use cls when we know it can only be Unicode?

Because you might want to subclass Unicode, and if you use cls then 
everything will just work correctly, but if you hard-code the name of 
the class, things will break.

Actually, my code has a bug. I wrote:

    return super(Unicode, cls).__new__(Unicode, *args)

in the __new__ method, but that hard-codes the name of the class. Let's 
try it:


>>> type(Unicode())  # Unicode class as defined in my previous post.
<class '__main__.Unicode'>
>>> class K(Unicode):
...     pass
...
>>> type(K())
<class '__main__.Unicode'>

Broken! I hang my head in shame :(

So you need to replace the above return with:

    return super(Unicode, cls).__new__(cls, *args)

and then it will work correctly:

>>> class K(Unicode):
...     pass
...
>>> type(K())
<class '__main__.K'>


You might be tempted to change the first reference to Unicode to cls as 
well, but sadly that does not work. The reason is complicated, and to 
be honest I don't remember it, but you will probably find it by 
googling for "python super gotchas".



-- 
Steven D'Aprano


More information about the Tutor mailing list