Python Setter throws Type Error. What is wrong here?

39 views Asked by At

I have a dataclass with an attribute 'open' of type float. I added a property setter which shall throw a ValueError in case it gets set to a negative value:

@open.setter
def open(self, value: float) -> None:
    if value < 0.0:
        raise ValueError("Open value must be positive.")
    self.open = value

The error I am getting is:

File "<string>", line 4, in __init__
  File "/home/PATH/file.py", line 29, in open
    if value < 0.0:
       ^^^^^^^^^^^
  TypeError: '<' not supported between instances of 'property' and 'float'

I don't really get what I am doing wrong here. Thanks for any advice!

1

There are 1 answers

0
J_H On

The OP was not a MRE.

The code below is. And it demonstrates a solution to the problem.

from dataclasses import dataclass


@dataclass
class Foo:
    def __init__(self):
        self._open: float = 2.718

    @property
    def open(self) -> float:
        return self._open

    @open.setter
    def open(self, value: float) -> None:
        if value < 0.0:
            raise ValueError("Open value must be positive.")
        self._open = value


if __name__ == "__main__":
    f = Foo()
    assert 2.718 == f.open
    f.open = 3.14
    assert 3.14 == f.open

The key is that you want self.open to be a setter method, so the (private) value belongs in a different object named self._open.


There's no conflict between these names and the popular builtin open(). But as a rule of thumb, it's typically a good idea to avoid such names. We steer clear of shadowing and human confusion.