python / python/mypy

conditioned `getattr` seems not understands defaults

Open
#17,647 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

it seems to me that the getattr with the default option is not parsed correctly so mypy complains that none is not allowed, but in fact it shall be (and it is) caught bu the exception

(A clear and concise description of what the bug is.)

To Reproduce

from typing import Optional

class Mine:
    better: Optional[bool]

def play() -> bool:
    m = Mine()
    if getattr(m, "better", None) is None:
        raise RuntimeError()
    return m.better

Expected Behavior

code shall be type-compatible

Actual Behavior

error: Incompatible return value type (got "bool | None", expected "bool")  [return-value]

Your Environment

  • Mypy version used: mypy==1.11.1
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied Python example with mypy 1.11.1 and inspect how the conditional getattr expression is analyzed. Done means the example type-checks without the reported return-value error, with a regression test covering the behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.