Skip to content

bad-return-type with "Actually returned: Any" even without --no-return-any #1859

@cebtenzzre

Description

@cebtenzzre

Description

I am using pytype 2024.10.11.

'foo' is just a placeholder in the below example; in the real code it is a file path that is passed through get_or_compute to the compute function and used as a cache key.

I would use the pytype equivalent of mypy's --no-warn-return-any to silence this kind of warning, but it seems like it's supposed to be opt-in in the first place (--no-return-any).

Possibly related (similar error): #1686 (comment)

Example Code

from typing import Any, Callable, Literal, TypeVar, overload

T = TypeVar('T')

class Cache:
    def __init__(self) -> None:
        self.cache: dict[str, dict[str, Any]] = {'foo': {}}

    @overload
    def get_or_compute(self, key: Literal['str'], compute: Callable[[], str]) -> str: ...

    @overload
    def get_or_compute(self, key: Literal['int'], compute: Callable[[], int]) -> int: ...

    def get_or_compute(self, key: str, compute: Callable[[], T]) -> T:
        entry = self.cache['foo']
        if key not in entry:
            entry[key] = compute()
        return entry[key]

cache = Cache()

def compute_str() -> str:
    print('computing str')
    return 'a'

def compute_int() -> int:
    print('computing int')
    return 1

def get_str() -> str:
    return cache.get_or_compute('str', compute_str)

def get_int() -> int:
    return cache.get_or_compute('int', compute_int)

print(f'int: {get_int()} str: {get_str()!r}')
print(f'int: {get_int()} str: {get_str()!r}')

Steps to Reproduce

$ python repr.py
computing int
computing str
int: 1 str: 'a'
int: 1 str: 'a'

$ mypy --strict --no-warn-return-any repr.py
Success: no issues found in 1 source file

$ pytype-single repr.py
repr.py:19:9: error: in get_or_compute: bad option 'int' in return type [bad-return-type]
           Expected: str
  Actually returned: Any

        return entry[key]
        ~~~~~~~~~~~~~~~~~

Called from (traceback):
  line 37, in current file
  line 32, in get_str

For more details, see https://google.github.io/pytype/errors.html#bad-return-type

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions