Thanks to visit codestin.com
Credit goes to github.com

Skip to content

False negative when using magic methods #8027

Closed
@fsouza

Description

@fsouza

Note: if you are reporting a wrong signature of a function or a class in
the standard library, then the typeshed tracker is better suited
for this report: https://github.com/python/typeshed/issues

Please provide more information to help us understand the issue:

  • Are you reporting a bug, or opening a feature request?

Bug?

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.
from typing import List
from typing import Optional


class CustomClass:
    def __getitem__(self, key: str) -> Optional[str]:
        pass


items: List[CustomClass] = []
[item["a"].strip() for item in items if item["a"] is not None]

The one below doesn't type check, as expected:

from typing import List
from typing import Optional


class CustomClass:
    def getitem(self, key: str) -> Optional[str]:
        pass


items: List[CustomClass] = []
[item.getitem("a").strip() for item in items if item.getitem("a") is not None]
  • What is the actual behavior/output?
Success: no issues found in 1 source file
  • What is the behavior/output you expect?

It should not type check, as repeated calls to __getitem__ are not guaranteed to return the same value.

  • What are the versions of mypy and Python you are using?
    Do you see the same issue after installing mypy from Git master?
% mypy --version
mypy 0.750+dev.1013b63eac2bef395952f2784fb3390dc181dec7
% python --version
Python 3.7.5
  • What are the mypy flags you are using? (For example --strict-optional)

--strict --scripts-are-modules

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions