typeddjango / django-stubs

PEP-484 stubs for Django
MIT License
1.56k stars 433 forks source link

Resources for annotating third party Django libraries #336

Open coiax opened 4 years ago

coiax commented 4 years ago

image

In our project, we're using django-enumfield, and their custom field.

Currently, the custom field is typed as an Any. The get type should be the specific Enum that you associate with the field, while the set type should be Union[int, MyEnum].

Some resources on how to write stubs for third party libraries would be really helpful!

sobolevn commented 4 years ago

You can try to use class-level attribute annotation with Field: https://github.com/typeddjango/django-stubs/blob/master/django-stubs/db/models/fields/__init__.pyi#L45

It is a generic type with two parameters:

Something like:

my_attr: Field[SupportsInt, str] = MyCustomIntField()

Can you please report if this works for you? If so, I will add this example to FAQ.

coiax commented 4 years ago

I tried to make a test setup, with the snippet you suggested, my results are in this gist.

https://gist.github.com/coiax/e4a26eb224c97b33cfb303f1df2f9fe0

Typing the field with Field[Union[int, Colour], Colour] only provides typing coverage when using an instance of the object, but looks like there's trouble with other ways of engaging with the object, unless I set up my test environment wrong!

sobolevn commented 4 years ago

Thanks! Can you please also attach mypy output to your gist?

coiax commented 4 years ago

Done.

flaeppe commented 11 months ago

With all of its quirks and limitations. Just as a reference, this is how I annotated a package with a model field: https://github.com/flaeppe/django-choicefield/