Emulating Final classes in Python

Antoon Pardon antoon.pardon at rece.vub.ac.be
Tue Jan 17 04:37:04 EST 2017


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
>
>
> It doesn't have to be absolutely bulletproof, but anyone wanting to subclass my 
> class should need to work for it, which hopefully will tell them that they're 
> doing something unsupported.
>
> Any hints?

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.

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)


So I wonder what reasons do you have prefering that your users monkey-patch your
class instead of subclassing it?

-- 
Antoon Pardon




More information about the Python-list mailing list