Open coiax opened 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:
_ST
for types that can be used when settings a value_GT
as a type that will be returned when getting a valueSomething 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.
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!
Thanks! Can you please also attach mypy
output to your gist?
Done.
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/
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 beUnion[int, MyEnum]
.Some resources on how to write stubs for third party libraries would be really helpful!