Emulating Final classes in Python
Steve D'Aprano
steve+python at pearwood.info
Wed Jan 18 20:36:51 EST 2017
On Thu, 19 Jan 2017 09:02 am, Ethan Furman wrote:
[...]
> One problem with the above is existing instances won't be modified to
> inherit from the updated class. I am unsure if that is solvable before
> 3.6, but in 3.6 one can use the new __init_subclass__ to avoid a Final
> base class, a FinalMeta type, and just update the existing class:
>
> def final(cls):
> def init_subclass(cls, **kwargs):
> raise Exception('Final class cannot be subclassed')
> cls.__init_subclass__ = classmethod(init_subclass)
> return cls
>
> This can be used as a decorator at class creation time, or at any later
> date to lock down a class. The downside is it's less obvious that the
> class is final... meaning there are no clues in the MRO.
Ah nice! I didn't know about __init__subclass__.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list