Skip to content

Commit

Permalink
Fix typing
Browse files Browse the repository at this point in the history
  • Loading branch information
bellini666 committed Jul 17, 2021
1 parent 9e384ed commit 5bec4aa
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 8 deletions.
11 changes: 9 additions & 2 deletions django_choices_field/fields.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Optional, Type

from django.core.exceptions import ValidationError
from django.db import models

Expand All @@ -8,7 +10,13 @@ class ChoicesField(models.CharField):
"invalid": "“%(value)s” must be a subclass of %(enum)s.",
}

def __init__(self, verbose_name=None, name=None, choices_enum=None, **kwargs):
def __init__(
self,
choices_enum: Type[models.TextChoices],
verbose_name: Optional[str] = None,
name: Optional[str] = None,
**kwargs,
):
self.choices_enum = choices_enum
kwargs["choices"] = choices_enum.choices
kwargs.setdefault("max_length", max(len(c.value) for c in choices_enum))
Expand All @@ -20,7 +28,6 @@ def deconstruct(self):
return name, path, args, kwargs

def to_python(self, value):
print(1, value, type(value))
if value is None:
return None

Expand Down
9 changes: 5 additions & 4 deletions django_choices_field/fields.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ from typing import (
Dict,
Generic,
Iterable,
Literal,
Optional,
Tuple,
Type,
Expand Down Expand Up @@ -78,7 +79,7 @@ class ChoicesField(Generic[_C], Field[_C, _C]):
def __get__(self: ChoicesField[_C], instance: Any, owner: Any) -> _C: ...
@overload
def __get__(self: ChoicesField[Optional[_C]], instance: Any, owner: Any) -> Optional[_C]: ...
@overload
def __set__(self, instance: ChoicesField[_C], value: _C) -> None: ...
@overload
def __set__(self, instance: ChoicesField[Optional[_C]], value: Optional[_C]) -> None: ...
# @overload
# def __set__(self, instance: ChoicesField[_C], value: _C) -> None: ...
# @overload
# def __set__(self, instance: ChoicesField[Optional[_C]], value: Optional[_C]) -> None: ...
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ multi_line_output = 3
force_sort_within_sections = true

[tool.pyright]
pythonVersion = "3.7"
pythonVersion = "3.8"
useLibraryCodeForTypes = true

[tool.pytest.ini_options]
Expand Down
2 changes: 1 addition & 1 deletion tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def test_set_none(db):
def test_set_wrong_value(db):
m = MyModel()
with pytest.raises(ValidationError) as exc:
m.c_field = 1
m.c_field = 1 # type:ignore (we really want the error here)
m.save()

assert list(exc.value) == ["“1” must be a subclass of <enum 'MyEnum'>."]

0 comments on commit 5bec4aa

Please sign in to comment.