nauer
nauer

Reputation: 700

How to annotate optional class properties correctly?

I have following example class with optional str 'abc'.

class ABC:
    def __init__(self, abc: Optional[str] = None) -> None:
        self.a = abc

    @property
    def a(self) -> str:
        return self._a

    @a.setter
    def a(self, abc: Optional[str]) -> None:
        if abc is None:
            self._a: str = "ABC"
        else:
            self._a = abc

'abc' is assigned to the @property a. The setter method tests if 'abc' is None and replaces it with a default string if so. So the return value of getter is always from type str and not optional anymore. But I could not find a way to annotate them correctly. I always got following mypy error:

Incompatible types in assignment (expression has type "Optional[str]", variable has type "str")

Upvotes: 1

Views: 352

Answers (1)

alex_noname
alex_noname

Reputation: 32053

As far as I know, properties with different getter and setter types have never been supported. See this discussion

I can suggest to use the same type or # type: ignore

Upvotes: 1

Related Questions