Skip to content Skip to sidebar Skip to footer

Python Creating A Readonly Wrapper Class Without Modifying Wrapped Class

I have a base class that looks like follows: class Base: def __init__(self, prop): self.prop = prop I want to create a wrapper class ReadonlyWrapper that is read-only,

Solution 1:

This can be achieved by overriding __setattr__ in the following way:

classReadonlyWrapper(Base):
    _initialized = False

    def__init__(self, *args, **kwargs):
        super(ReadonlyWrapper, self).__init__(*args, **kwargs)
        self._initialized = True

    def__setattr__(self, key, value) -> None:ifself._initialized:
            raise PermissionError()
        else:super().__setattr__(key, value)

Once _initialized is set to True, any attempt to set an attribute will raise a PermissionError.

Post a Comment for "Python Creating A Readonly Wrapper Class Without Modifying Wrapped Class"