type(d) != type(d.copy()) when type(d).issubclass(dict)

Duncan Booth duncan.booth at invalid.invalid
Sat Dec 25 10:58:35 EST 2010


kj <no.email at please.post> wrote:

> Watch this:
> 
>>>> class neodict(dict): pass
> ... 
>>>> d = neodict()
>>>> type(d)
><class '__main__.neodict'>
>>>> type(d.copy())
><type 'dict'>
> 
> 
> Bug?  Feature?  Genius beyond the grasp of schlubs like me? 

Feature.

In (almost?) all cases any objects constructed by a subclass of a builtin 
class will be of the original builtin class. So, for example, subclass a 
string and concatenating your subclassed objects still produces a string.

This is reasonable behaviour as for builtin classes performance is more 
important than fully implementing polymorphism. If you want to subclass a 
builtin class you need to be aware of this and override the behaviour where 
it matters.

Why do you want to subclass a dict anyway? It is usually the wrong choice.


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list