Skip to content

mypy should understand that setters can accept wider types than their getter returns #19057

Closed
@warsaw

Description

@warsaw

Bug Report

Apologies in advance if this has already been reported. I tried to search the tracker but my search-fu must not be good enough.

mypy should allow property setters to accept compatible but wider types than their property getter returns. mypy 1.50.0 returns this error:

lock.py:11: error: Incompatible types in assignment (expression has type "timedelta | int", variable has type "timedelta")  [assignment]
Found 1 error in 1 file (checked 1 source file)

but it should be allowed, since self._lifetime is always guaranteed to be a timedelta and therefore the getter's return type should always be correct.

To Reproduce

from datetime import timedelta

type Interval = timedelta | int

DEFAULT_LIFETIME = timedelta(seconds=3)


class Lock:
    def __init__(self, lifetime: Interval | None = None):
        self._lifetime: timedelta
        self.lifetime = DEFAULT_LIFETIME if lifetime is None else lifetime

    @property
    def lifetime(self) -> timedelta:
        return self._lifetime

    @lifetime.setter
    def lifetime(self, lifetime: Interval) -> None:
        if isinstance(lifetime, timedelta):
            self._lifetime = lifetime
        else:
            self._lifetime = timedelta(seconds=lifetime)

Expected Behavior

I wouldn't expect mypy to complain about line 11.

Actual Behavior

See above for the error. It's easy enough to add a typing: ignore[assignment] to line 11, but that doesn't seem like it should be necessary.

Your Environment

  • Mypy version used: 1.15.0 (compiled: yes)
  • Mypy command-line flags: mypy lock.py
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: Python 3.13.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions