samedi 4 février 2023

Python class function return super()

So I was messing around with a readonly-modifyable class pattern which is pretty common in java. It involves creating a base class containig readonly properties, and extending that class for a modifyable version. Usually there is a function readonly() or something simular to revert a modifyable-version back to a readonly-version of itself.

Unfortunately you cannot directly define a setter for a property defined in a super class in python, but you can simply redefine it as shown below. Mor interestingly In python you got the 'magic function' super returning a proxy-object of the parent/super class which allows for a cheecky readonly() implementation which feels really hacky, but as far as I can test it just works.

class Readonly:
    _t:int
    
    def __init__(self, t: int):
        self._t = t
    
    @property
    def t(self) -> int:
        return self._t



class Modifyable(Readonly):
    def __init__(self, t: int):
        super().__init__(t)
    
    @property
    def t(self) -> int:
        return self._t # can also be super().t
    
    @t.setter
    def t(self, t):
        self._t = t
    
    def readonly(self) -> Readonly:
        return super()

In the above pattern I can call the readonly function and obtain a proxy to the parent object without having to instantiate a readonly version. The only problem would be that when setting the readonly-attribute instead of throwing AttributeError: can't set attribute, it will throw a AttributeError: 'super' object has no attribute '<param-name>'

So here are the question for this:

  • Can this cause problems (exposing the super proxy-object outside the class itself)?
  • I tested this on python 3.8.5, but not sure if that is by accident and goes against the 'python-semantics' so to speak?
  • Is there a better/more desirable way to achieve this? (I have no idea if its even worth the ambiguous error message in ragards to performance for example)

I Would love to hear opinions and/or insights into this

Aucun commentaire:

Enregistrer un commentaire