Emulating Final classes in Python
steve+comp.lang.python at pearwood.info
Tue Jan 17 21:10:41 EST 2017
On Tuesday 17 January 2017 20:37, Antoon Pardon wrote:
> Op 17-01-17 om 08:05 schreef Steven D'Aprano:
>> I wish to emulate a "final" class using Python, similar to bool:
>> py> class MyBool(bool):
>> ... pass
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> TypeError: type 'bool' is not an acceptable base type
> I find those kind of classes annoying as hell and nobody has ever given me a
> good reason for them. What good was it to change Lock from a factory function
> to a class if you can't subclass the result anyway.
I'm not sure which Lock class you're referring to.
> The result will probably be that users that would prefer to subclass your
> class will monkey-patch it. Something like:
> class MyLock:
> def __init__(self):
> self.lock = Lock()
> def __getattr__(self, attr):
> return getattr(self.lock, attr)
That technique is called "delegation", or sometimes "composition".
> So I wonder what reasons do you have prefering that your users monkey-patch
> your class instead of subclassing it?
Since my class provides no useful behaviour, I don't think anyone will
seriously have any reason to subclass it.
Python has at least three singleton instances which are used purely as abstract
symbols: they have no state, and very little behaviour besides a nice repr.
They are None, NotImplemented and Ellipsis. I'm effectively trying to make my
own abstract symbol.
But it's mostly a learning exercise.
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." - Jon Ronson
More information about the Python-list