Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
cebtenzzre opened this issue Jan 2, 2025 · 0 comments

Comments

@cebtenzzre
Copy link

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant