subclassable types

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Feb 22 05:54:30 EST 2013


On Fri, 22 Feb 2013 09:35:25 +0000, Wolfgang Maier wrote:

> Dear all,
> I am wondering what the rules are that determine whether a built-in type
> is subclassable or not.

The type-designer thought it should, or shouldn't, be.


> As examples, why can you base your classes on int or set, but not on
> bool or range?

In the case of bool, because of the rule that bool is a singleton 
(actually, "doubleton") class. Since a bool subclass would have 
instances, that would break the rule that there is only one true bool and 
one false bool.

As for range, I'm not sure. It may not be a deliberate decision, but a 
side-effect of the implementation. I have a vague recollection of there 
being a difference between "heap types" and "non-heap types", which has 
probably got something to do with the C implementation. 

If that's the case, I see that both Jython and IronPython have treated 
this as a language restriction rather than an accident. IronPython 
especially is interesting:

>>> class foo(xrange):  # equivalent to range in Python3
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot derive from IronPython.Runtime.XRange because it is 
sealed



> Also: can you use introspection to find out whether a type is valid as a
> base type?

I don't believe so, but welcome correction. I would just try. If it 
succeeds, it will succeed, otherwise it will raise TypeError.



-- 
Steven



More information about the Python-list mailing list