How does python prevent a subclass of a class?

In python docs, I found the following:

BOOL ([x])

Convert the value to a boolean using the standard truth-checking procedure. If x is false or omitted, this returns False; otherwise returns True. bool is also a class that is a subclass of int. The bool class cannot be further subclassed. Its only copies are False and True.

I never wanted a subclass of bool in my life, but naturally I tried it right away and of course

 >>> class Bool(bool): pass Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> class Bool(bool): TypeError: Error when calling the metaclass bases type 'bool' is not an acceptable base type 

So the question is: how is this done? Can I apply the same technique (or another) to mark my own classes as final , i.e. So that they are not subclassed?

+7
source share
1 answer

The bool type is defined in C, and its tp_flags slot intentionally does not include the Py_TPFLAGS_BASETYPE flag.

C types must explicitly denote themselves as subclasses.

To do this for custom Python classes, use the metaclass:

 class Final(type): def __new__(cls, name, bases, classdict): for b in bases: if isinstance(b, Final): raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__)) return type.__new__(cls, name, bases, dict(classdict)) class Foo: __metaclass__ = Final class Bar(Foo): pass 

gives:

 >>> class Bar(Foo): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in __new__ TypeError: type 'Foo' is not an acceptable base type 
+13
source

All Articles