12

Possible Duplicate:
Final classes in Python 3.x- something Guido isn't telling me?

I was watching a talk (How to design a good API and why it matters) in which it was said, literally, "design and document for inheritance, else prohibit it". The talk was using Java as an example, where there's the 'final' keyword for prohibiting subclassing. Is it possible to prohibit subclassing in Python? If yes, it'd be great to see an example... Thanks.

Community
  • 1
  • 1
aeter
  • 11,960
  • 6
  • 27
  • 29

2 Answers2

21

There is no Python keyword for this - it is not Pythonic.

Whether a class can be subclassed is determined by a flag called Py_TPFLAGS_BASETYPE which can be set via the C API.

This bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar to a “final” class in Java).

You can however emulate the behaviour using only Python code if you wish:

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 C(metaclass=Final): pass

class D(C): pass

Source

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Thank you, I think this is what I was asking for. Also, I was searching for similar questions, but wasn't able to find anything, so I posted the question. – aeter Oct 16 '10 at 13:14
  • I don't know in which version of Python you can use the syntax for class C but I had to change for version 2.5 as: class C(object): __metaclass__ = Final To make it work. – Pierre Thibault Apr 17 '11 at 00:00
  • 1
    i wish people would stop using "it is not Pythonic" as an excuse for things that just haven't been implemented yet. https://www.python.org/dev/peps/pep-0591/#the-final-decorator – Edward Mar 25 '20 at 14:54
  • @PierreThibault: The OP's answer is Python 3 metaclass syntax, yours is Python 2. – ShadowRanger May 08 '21 at 00:21
12

In my opinion, classes should generally not have any subclassing restrictions at all. I would like to suggest the third option: Add a comment in your class' documentation that states that the class is not meant to be subclassed.

steinar
  • 9,383
  • 1
  • 23
  • 37