7
votes

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.

2
Now I just have to post this link I just read when asking a related question a few minutes ago: steve-yegge.blogspot.com/2010/07/… - Klaus Byskov Pedersen
Okay, so you can. But you shouldn't, lest you violate all idioms and anger all Python users. - user395760
@delnan - I was just wondering whether I can do it at all. - aeter

2 Answers

15
votes

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

11
votes

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.