KEMBAR78
Assignment to an instance backed by a descriptor doesn't discard optional · Issue #5851 · python/mypy · GitHub
Skip to content

Assignment to an instance backed by a descriptor doesn't discard optional #5851

@gvanrossum

Description

@gvanrossum

Universal example:

from typing import Type, TypeVar, Optional
T = TypeVar('T')

class IntDescr:
  def __get__(self, obj: T, typ: Type[T]) -> Optional[int]: ...
  def __set__(self, obj: T, value: Optional[int]) -> None: ...

class C:
  reg = 0
  spec = IntDescr()

  def meth_reg(self) -> int:
    if self.reg is None:
      self.reg = 0
    return self.reg    # OK

  def meth_spec(self) -> int:
    if self.spec is None:
      self.spec = 0
    # assert self.spec is not None
    return self.spec    # Error: Incompatible return value type (got "Optional[int]", expected "int")

If I uncomment the assert on the line before the error, the error goes away. I suspect that something is missing for assignment to descriptors. Or perhaps this is intentional, because we can't be sure that __set__ doesn't just throw the value away? Then the assert would be an unfortunate workaround needed 99% of the time.

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions