pytype icon indicating copy to clipboard operation
pytype copied to clipboard

Descriptors don't work when imported from another module

Open eltoder opened this issue 2 years ago • 0 comments

Consider the following example, which has to be split in 2 files:

ids.py

from typing import Callable, Optional, overload

class Base:
    id: "ClassId"

class ClassId:
    @overload
    def __get__(self, obj: None, owner: type) -> "ClassId":
        ...

    @overload
    def __get__(self, obj: Base, owner: Optional[type] = None) -> Callable[[], int]:
        ...

    def __get__(self, obj, owner=None):
        if obj is None:
            return self
        return lambda: 123

class_ids2.py

from ids import Base

def test(x: Base) -> int:
    reveal_type(x.id)
    return x.id()

This produces an error in pytype, because descriptor protocol is not applied to x.id:

$ pytype class_id2.py
...
File "/home/eltoder/dev/scratch/class_id2.py", line 4, in test: ids.ClassId [reveal-type]
File "/home/eltoder/dev/scratch/class_id2.py", line 5, in test: 'ClassId' object is not callable [not-callable]

However, if I put everything in one file and remove the import, it works as expected:

$ pytype class_id2.py
...
File "/home/eltoder/dev/scratch/class_id2.py", line 21, in test: Callable[[], int] [reveal-type]

The original example with an import works fine in mypy:

$ mypy class_id2.py
class_id2.py:4: note: Revealed type is "def () -> builtins.int"

eltoder avatar Jul 26 '23 21:07 eltoder