Skip to content
Advertisement

Python property setter only

I have a class with property decorator.

class Dispatcher:
    def __init__(self, url):
        self._session = None

    @property
    def session(self):
        return self._session

    @session.setter
    def session(self, value):
        self._session = value

But I don’t need the getter, can I have property with only the setter?

It’s most more a curiosity.

Advertisement

Answer

The simplest way IMHO is

class Dispatcher:
    def __init__(self, url):
        self._session = None

    def _set_session(self, value):
        self._session = value

    session = property(fset=_set_session)

Demo:

>>> d = Dispatcher('a')
>>> d.session = 1
>>> d._session
1
>>> d.session
Traceback (most recent call last):
  File "<pyshell#81>", line 1, in <module>
    d.session
AttributeError: unreadable attribute
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement