Skip to content

Generic type is not inferred across descriptor class methods #8516

Closed
@sjustas

Description

@sjustas

Tried to write type stubs for lazy package. Lazy provides a descriptor that invokes the underlying method only once and caches the result in the instance.

The inferred type is <nothing>, so mypy crashes when checking expressions.

from typing import Any, Generic, Callable, TypeVar

T = TypeVar('T')

class lazy:
    def __init__(self, func: Callable[[Any], T]) -> None: ...
    def __get__(self, inst: Any, inst_cls: Any) -> T: ...

class Haystack:
    @lazy
    def hasNeedles(self) -> bool:
        # some expensive lookup we want to execute only once
        return True

reveal_type(Haystack().hasNeedles)

# checking this expression crashes
x = Haystack().hasNeedles or True
<...>
note: Revealed type is '<nothing>'
<...>
version: 0.761
Traceback (most recent call last):
  File "mypy/checkexpr.py", line 3645, in accept
  File "mypy/nodes.py", line 1736, in accept
  File "mypy/checkexpr.py", line 2029, in visit_op_expr
  File "mypy/checkexpr.py", line 2662, in check_boolean_op

If lazy was defined as a function, type gets inferred correctly.

def lazy(func: Callable[[Any], T]) -> T: ...
note: Revealed type is 'builtins.bool*'

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions