[Django]-Inherit choice class to extend it?

3👍

You need to unpack the ones from the parent. You do that with an asterisk (*):

class ExtendedChoices(UserChoices):

    OTHER_CHOICE = "other_choice"

    @classmethod
    def choices(cls):
        return (
            *UserChoices.choices(),  # ← an asterisk to unpack the tuple
            (cls.OTHER_CHOICE, _("Other choice")),
        )

If we unpack a tuple in another tuple, we construct a tuple that contains all the items of the unpacked tuple as elements of the new tuple. For example:

>>> x = (1,4,2)
>>> (x, 5)
((1, 4, 2), 5)
>>> (*x, 5)
(1, 4, 2, 5)

If we thus do not use an asterisk, it will simply see x as a tuple, and we thus construct a 2-tuple with as first element the tuple x.

If we unpack the first tuple, we obtain a 4-tuple where the first three elements originate from x followed by 5.

Leave a comment