Opened 3 years ago

Closed 3 years ago

#33193 closed Cleanup/optimization (invalid)

Clarify enumeration types are true Python Enums

Reported by: johnthagen Owned by: nobody
Component: Documentation Version: 3.2
Severity: Normal Keywords: enum
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

https://docs.djangoproject.com/en/3.2/ref/models/fields/#field-choices-enum-types

I was originally hesitant to use the Django "enumeration fields" when I first read about them because to me the documentation made it sound like they were "similar" to Python Enums, but something different. I value using core data types for interop with other non-Django specific code, so I continued to use django-enumfields (https://github.com/hzdg/django-enumfields) for several releases. This allowed me to use true Python Enums which are familiar to use to developers not as versed in Django.

Recently I dug into the Django source code more deeply after hearing about them again and discovered that indeed the Choices type is really just an Enum with a little extra magic and some extra helper methods applied to them (and as such can be used as a normal Python Enum as well).

class ChoicesMeta(enum.EnumMeta):
    """A metaclass for creating a enum choices."""

...

class Choices(enum.Enum, metaclass=ChoicesMeta):
    """Class for creating enumerated choices."""

I would recommend modifying the docs in some way, for example:

These work similar to enum from Python’s standard library, but with some modifications:

Could be reworded:

These are true Enums from Python's standard library, but with some additional extensions added:

Change History (2)

comment:1 by johnthagen, 3 years ago

Continuing some research, I learned that Django won't return an Enum instance from a field decorated using a Choices Enum (as described at the bottom of https://stackoverflow.com/a/58051918), unlike django-enumfields (https://pypi.org/project/django-enumfields/). Since the user doesn't get an Enum instance back out directly, perhaps the way the docs are currently worded is in fact appropriate.

comment:2 by Mariusz Felisiak, 3 years ago

Resolution: invalid
Status: newclosed

Yeah, I think the current form is more appropriate.

Note: See TracTickets for help on using tickets.
Back to Top