# Python Final Class [[Python]] implementation of [[Final Class]]. ```python class MetaFinal(type): def __new__(cls, name: str, bases: tuple[type, ...], dict_: dict) -> type: for base in bases: if isinstance(base, MetaFinal): raise TypeError( f"type '{base.__name__}' is Final and cannot " f"be extended or inherited" ) if '__slots__' not in dict_: raise TypeError(f"Class '{name}' must define __slots__") return type.__new__(cls, name, bases, dict_) ``` ## Usage ### Minimal final class A minimal [[Final Class]] will prevent [[Subclass|subclassing]]. ```python class Foo(metaclass=MetaFinal): __slots__ = () class Fii(Foo): pass # TypeError: type 'Foo' is Final and cannot be extended or inherited ``` ### Mutable object attribute [[Final Class]] allows to [[Mutability|mutate]] [[Object]] [[Attribute|attributes]]. ```python class Bar(metaclass=MetaFinal): __slots__ = ("biz") b = Bar() b.biz = 3.14 # Good ``` ### Read-only methods [[Final Class]] prevent [[Method]] [[Override]]. ```python class Bar(metaclass=MetaFinal): __slots__ = () def biz(self): return self.__class__.__name__ b = Bar() b.biz = lambda _: "hello" # AttributeError: 'Bar' object attribute 'biz' is read-only ``` ### Read-only class [[Final Class]] prevent extending instances with new attributes or methods. ```python f = Foo() f.fiz = "hello" # AttributeError: 'Foo' object has no attribute 'fiz' ``` ### Read-only class attributes [[Final Class]] prevent mutating attributes that belongs to the class and not instances. ```python class Bar(metaclass=MetaFinal): __slots__ = () biz = 42 b = Bar() b.biz = 3.14 # AttributeError: 'Bar' object attribute 'biz' is read-only ``` --- Bibliography: - [Title - website.com](need bibliography)