0

One of my methods takes a status argument that's used in a filter().

This argument is related to a model field defined like this :

STATUS_CHOICES = (
    (1, _("draft")),
    (2, _("private")),
    (3, _("published")),
)

class MyModel(Model):
    status = models.PositiveSmallIntegerField(_("status"), choices=STATUS_CHOICES, default=1)

I'd like to use Python's type hints in order to make its definition clearer.

I could probably do something like :

def my_method(status: int):
   ...

But the status has to be included in STATUS_CHOICES.

Can I make this hint more restrictive and limited to STATUS_CHOICES values?

vmonteco
  • 14,136
  • 15
  • 55
  • 86
  • 1
    Does this answer your question? [typing: Dynamically Create Literal Alias from List of Valid Values](https://stackoverflow.com/questions/64522040/typing-dynamically-create-literal-alias-from-list-of-valid-values) – MisterMiyagi Nov 23 '21 at 16:14
  • Another option, especially for ints is to define an [`IntEnum`](https://docs.python.org/3/library/enum.html#enum.IntEnum) – joshmeranda Nov 23 '21 at 16:16
  • Hello @MisterMiyagi , hello @joshmeranda , thank you for the suggestions but it looks like the approved answer suggests to redefine my `STATUS_CHOICES`, which, for historical reasons, I can't really do. – vmonteco Nov 24 '21 at 08:55
  • If you really want "has to be included in ``STATUS_CHOICES``" and not, say, manually *duplicate* the relevant parts of ``STATUS_CHOICES``, there is no way to create a static type definition, then. – MisterMiyagi Nov 24 '21 at 08:57
  • @MisterMiyagi Ideally, I would have liked to make the admitted values defined from `MyModel.status.choices`, but that may be too much. I'd say that "duplicating the relevant parts of `STATUS_CHOICES`" may be a good solution if it doesn't imply hard-coding the duplicate (if when modifying the `STATUS_CHOICES` the allowed values follow the change). – vmonteco Nov 24 '21 at 09:20
  • 1
    It would require hardcoding the duplicate. ``STATUS_CHOICES`` is a value, i.e. dynamic information, it cannot be used to define a type, i.e. static information. – MisterMiyagi Nov 24 '21 at 09:25
  • I see, then thank you. I'll just use an "`int`". – vmonteco Nov 24 '21 at 09:46

0 Answers0