Emulating Final classes in Python
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Jan 18 02:05:33 EST 2017
On Wednesday 18 January 2017 15:42, Ethan Furman wrote:
[...]
> Both those cases are good candidates for disallowing subclassing.
I've given a metaclass that disallows subclassing:
class MyClass(MyParent, metaclass=FinalMeta):
...
Ethan took that one step further by giving a class you inherit from to disallow
subclassing:
class MyClass(MyParent, Final):
...
Could we solve this problem with a decorator?
@final
class MyClass(MyParent):
...
Without needing to add any special magic to MyParent or MyClass, apart from the
decorator, can we make MyClass final? That would (in principle) allow us to
make a subclass, and *then* set the class final so that no more subclasses
could be made.
I thought that the decorator could simply set the class' metaclass:
def final(cls):
if cls.__class__ is type:
cls.__class__ = Meta
return cls
raise TypeErrror('Possible metaclass conflict')
but that's disallowed. Any ideas?
--
Steven
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." - Jon Ronson
More information about the Python-list
mailing list