0

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, with the following functionality:

# Create instance using __init__ of base class.
readonly_instance = ReadonlyWrapper()

# I can access properties
prop = readonly_instance.prop

# This should raise a PermissionError
readonly_instance.prop = 23

More precisely I want that all field of the class are read-only, but only after __init__ is called, otherwise the class cannot be constructed in the constructor itself. I know it can be done using the property decorator, but I do not want to turn all attributes into properties.

1 Answers1

0

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

class ReadonlyWrapper(Base):
    _initialized = False

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

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

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