Single type getter with a multi type setter in Mypy and Pyright

I have a piece of code that looks like the following:

class Obj:
    def __init__(self, prop) -> None:
        self.prop = prop

    @property
    def prop(self) -> str:
        # Imagine logic here to gurantee that prop is always `str`
        return str(self.prop)
    
    @prop.setter
    def prop(self, value) -> None:
        self.prop = value

The original code base is untyped. The author, despite admitting to not be interested in type hints, agreed to including type stubs.

Here’s what the stubs look like:

class Obj:
    def __init__(self, prop: str | int | None) -> None: ...
    @property
    def prop(self) -> str: ...
    @prop.setter
    def prop(self, value: str | int | None) -> None: ...

Pyright handles it without issues. (Playground)
Mypy, however, does not. (Playground)

I do want to support mypy but unsure of how to proceed from here. I cannot change the implementation itself, so I’m limited to the type stubs.

Mypy will support this in its next release. See Support properties with setter type different from getter type by ilevkivskyi · Pull Request #18510 · python/mypy · GitHub

4 Likes

Good to know that support for this is on the way. In the meantime you can use something like what I did for types-WebOb and define an asymmetric descriptor Protocol: typeshed/stubs/WebOb/webob/_types.pyi at main · python/typeshed · GitHub

1 Like

Finding out my exact issue is getting fixed next release is like a present! :smile:
Thank you.

This works for now, thank you.