[Python] Subclass that throws custom error if modified

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    What's the best way in python to create a subclass of an existing class, in such a way that a custom error is raised whenever you attempt to modify the object?

    The code below shows what I want.

    class ImmutableModifyError(Exception):
    pass

    class ImmutableList(list):
    def __init__(self, err = "", *argv):
    self.err = err
    super().__init__(*argv)

    def append(self, *argv):
    raise ImmutableModifyError(self.err)

    def extend(self, *argv):
    raise ImmutableModifyError(self.err)

    def clear(self, *argv):
    raise ImmutableModifyError(self.err)

    def insert(self, *argv):
    raise ImmutableModifyError(self.err)

    def pop(self, *argv):
    raise ImmutableModifyError(self.err)

    def remove(self, *argv):
    raise ImmutableModifyError(self.err)

    def sort(self, *argv):
    raise ImmutableModifyError(self.err)

    def reverse(self, *argv):
    raise ImmutableModifyError(self.err)


    If I use other immutable types, an AttributeError is thrown instead of the custom error whose message is created along the object. As you can see, this code is too repetitive and would be error-prone if the class changed. I have not taken into account hidden methods and operators. Is there a better way to achieve this?

    Continue reading...

Compartilhe esta Página