Which classes cannot be subclassed?

Question:

Is there any rule about which built-in and standard library classes are not subclassable (“final”)?

As of Python 3.3, here are a few examples:

  • bool
  • function
  • operator.itemgetter
  • slice

I found a question which deals with the implementation of “final” classes, both in C and pure Python.

I would like to understand what reasons may explain why a class is chosen to be “final” in the first place.

Asked By: max

||

Answers:

There seems to be two reasons for a class to be “final” in Python.

1. Violation of Class Invariant

Classes that follow Singleton pattern have an invariant that there’s a limited (pre-determined) number of instances. Any violation of this invariant in a subclass will be inconsistent with the class’ intent, and would not work correctly. Examples:

  • bool: True, False; see Guido’s comments
  • NoneType: None
  • NotImplementedType: NotImplemented
  • ellipsis: Ellipsis

There may be cases other than the Singleton pattern in this category but I’m not aware of any.

2. No Persuasive Use Case

A class implemented in C requires additional work to allow subclassing (at least in CPython). Doing such work without a convincing use case is not very attractive, so volunteers are less likely to come forward. Examples:

Note 1:

I originally thought there were valid use cases, but simply insufficient interest, in subclassing of function and operator.itemgetter. Thanks to @agf for pointing out that the use cases offered here and here are not convincing (see @agf comments to the question).

Note 2:

My concern is that another Python implementation might accidentally allow subclassing a class that’s final in CPython. This may result in non-portable code (a use case may be weak, but someone might still write code that subclasses function if their Python supports it). This can be resolved by marking in Python documentation all built-in and standard library classes that cannot be subclassed, and requiring that all implementations follow CPython behavior in that respect.

Note 3:

The message produced by CPython in all the above cases is:

TypeError: type 'bool' is not an acceptable base type

It is quite cryptic, as numerous questions on this subject show. I’ll submit a suggestion to add a paragraph to the documentation that explains final classes, and maybe even change the error message to:

TypeError: type 'bool' is final (non-extensible)
Answered By: max

if we check for the builtins (excluding errors, dunder methods, warnings; one could include them also if required)

import keyword, re
x = sorted([i for i in list(keyword.__builtins__) if not re.search('.*Error|Warning|__', i)], key=len)

and then run,

l1 = []
l2 = []
for i in x:
  try:
    A = type('A', (eval(i),), {})
    l1.append(i)
  except TypeError:
    l2.append(i)

then,

l1

gives,

['int', 'map', 'set', 'str', 'zip', 'dict', 'list', 'type', 'bytes', 'float',
 'super', 'tuple', 'filter', 'object', 'complex', 'property', 'reversed',
 'bytearray', 'enumerate', 'frozenset', 'Exception', 'SystemExit',
 'classmethod', 'staticmethod', 'BaseException', 'StopIteration',
 'GeneratorExit', 'KeyboardInterrupt', 'StopAsyncIteration']

while,

l2

gives,

['id', 'abs', 'all', 'any', 'bin', 'chr', 'dir', 'hex', 'len', 'max', 'min',
 'oct', 'ord', 'pow', 'sum', 'eval', 'exec', 'hash', 'iter', 'next', 'repr',
 'vars', 'None', 'True', 'bool', 'open', 'help', 'ascii', 'input', 'print',
 'round', 'False', 'range', 'slice', 'divmod', 'format', 'locals', 'sorted',
 'compile', 'delattr', 'getattr', 'globals', 'hasattr', 'setattr', 'credits',
 'license', 'display', 'runfile', 'dreload', 'callable', 'Ellipsis', 'execfile',
 'copyright', 'breakpoint', 'isinstance', 'issubclass', 'memoryview',
 'get_ipython', 'NotImplemented']

the list l1 contains builtins which could act as a base class.

Answered By: apostofes