Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python prevent a class from being subclassed? [duplicate]

I came across the following in the python docs:

bool([x])

Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True.

I've never in my life wanted to subclass bool, but naturally I immediately tried it, and sure enough:

>>> 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: How is this done? And can I apply the same technique (or a different one) to mark my own classes as final, i.e., to keep them from being subclassed?

like image 659
alexis Avatar asked Apr 17 '13 09:04

alexis


People also ask

What is a subclass in Python?

This means that an object of a subclass can access all the attributes and methods of the superclass. Moreover, subclass may have its own attributes or methods in addition to the inherited ones as well. Let's learn to create a subclass in Python.

How to use Python classes effectively?

How to use Python classes effectively 1 Python classes: the very basics. Classes are objects that allow you to group data structures and procedures in one place. ... 2 Classes are amazing — in theory. ... 3 When classes are a bad idea. ... 4 The bottom line: Python classes are a two-edged sword. ...

What is the difference between superclass and subclass?

Other names of superclass are base class or parent class, and other names of subclass are derived class or child class. In our Rectangle example, Rectangle is the superclass and Square is its subclass. The process of creating a subclass of a class is called inheritance.

What is a class in Python?

Classes are objects that allow you to group data structures and procedures in one place. For example, imagine you’re writing a piece of code to organize the inventory of a clothes shop. You could create a class that takes each item of clothing in the shop, and stores key quantities such as the type of clothing, and its color and size.


1 Answers

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

C types need to mark themselves explicitly as subclassable.

To do this for custom Python classes, use a 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
like image 117
Martijn Pieters Avatar answered Oct 11 '22 22:10

Martijn Pieters