Skip to content

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

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

fromdatetimeimporttimedelta
type Interval=timedelta|intDEFAULT_LIFETIME=timedelta(seconds=3)
classLock:
def__init__(self, lifetime: Interval|None=None):
self._lifetime: timedeltaself.lifetime=DEFAULT_LIFETIMEiflifetimeisNoneelselifetime@propertydeflifetime(self) ->timedelta:
returnself._lifetime@lifetime.setterdeflifetime(self, lifetime: Interval) ->None:
ifisinstance(lifetime, timedelta):
self._lifetime=lifetimeelse:
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