Which of these metaclasses should be preferred, and is there room for improvement?

Some people are not familiar with the philosophies that come with working in Python and have a desire embedded in them from other languages that allow them to make it impossible to inherit from and extend a class through subclassing. Python has no builtin in way of preventing this but can be supplemented with comments or other documentation that explains that a class should not be part of an inheritance tree. Alternatively, some programmers with backgrounds in other languages may require the use of a metaclass to prevent subclassing when appropriate.

Assuming a project's leader would not budge on the use of metaclasses for such a purpose but was open to alternate implementations, which of the following is better at following best practices targeted at Python? Both are rather simple, so another question may be difficult to answer: can either be improved?

First Metaclass

class SealedMeta(type):
    """SealedMeta(name, bases, dictionary) -> new sealed class"""
    __REGISTRY = ()

    def __new__(mcs, name, bases, dictionary):
        """Create a new class only if it is not related to a sealed class."""
        if any(issubclass(base, mcs.__REGISTRY) for base in bases):
            raise RuntimeError('no class may inherit from a sealed class')
        mcs.__REGISTRY += (super().__new__(mcs, name, bases, dictionary),)
        return mcs.__REGISTRY[-1]

Second Metaclass

class Final(type):
    """Final(name, bases, dictionary) -> new final class"""

    def __new__(mcs, name, bases, dictionary):
        """Create a new class if none of its bases are marked as final."""
        if any(isinstance(base, mcs) for base in bases):
            raise TypeError('no class may inherit from a final class')
        return super().__new__(mcs, name, bases, dictionary)
  • 1
    \$\begingroup\$ Oh, this brings back memories... --Doctor, it hurts me if I do this! --Oh, Lord, stop doing this! \$\endgroup\$ – wvxvw Nov 28 '17 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.