typeddjango / django-stubs

PEP-484 stubs for Django
MIT License
1.6k stars 450 forks source link

Custom field typing #545

Open markedwards opened 3 years ago

markedwards commented 3 years ago

Bug report

I'm trying to implement generic typing on custom fields, and I'm not having much luck. Any idea if there is a way to make this work?

What's wrong

Note: The following examples require hacking django_stubs_ext.patch._need_generic to include django.db.models.Field, which is something I'll raise separately.

I'm able to specify static typing for a custom field, but I'm not able to specify generic typing. Example code:

class FooField(Field[List[float], List[float]]):
    ... code that implements field storage for a list of floats ...

T = TypeVar('T', bound=Union[float, int])

class BarField(Field[List[T], List[T]]):
    def __init__(self, base_type: Type[T], *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        self._base_type = base_type

    ... code that implements field storage for a list of T ...

class MyModel(Model):
    foo = FooField()
    bar = BarField(float)

def get_foo_item(model: MyModel, i: int) -> float:
    return model.foo[i]  # No error

def get_bar_item(model: MyModel, i: int) -> float:
    return model.bar[i]  # mypy error: Returning Any from function declared to return "float"

How is that should be

Have I missed something in my implementation, or is this not supported?

System information

TylerYep commented 3 years ago

I have the same issue. Does anyone know how to get this working?

markedwards commented 2 years ago

This is still happening in the latest release. Is this not considered to be a bug?

bryanhelmig commented 2 years ago

Same question over here...

provinzkraut commented 1 year ago

I'm currently facing the same issue, which I believe to be related to what's described in #336.

Any insights or updates on this? @sobolevn maybe? :) I've already looked into the code here and as far as I can tell, mypy should be able to pick up the bound types for the generics. If there are any pointers as to what might be needed to support this I'd be happy to contribute as well.