{"id":13501737,"url":"https://github.com/loggi/python-choicesenum","last_synced_at":"2025-04-07T13:07:29.762Z","repository":{"id":24312582,"uuid":"101131665","full_name":"loggi/python-choicesenum","owner":"loggi","description":"Python's Enum with extra powers to play nice with labels and choices fields.","archived":false,"fork":false,"pushed_at":"2024-07-01T16:50:13.000Z","size":161,"stargazers_count":80,"open_issues_count":5,"forks_count":11,"subscribers_count":154,"default_branch":"master","last_synced_at":"2025-03-31T10:09:47.462Z","etag":null,"topics":["choices","custom-fields","django","enum","python"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/loggi.png","metadata":{"files":{"readme":"README.rst","changelog":"HISTORY.rst","contributing":"CONTRIBUTING.rst","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS.rst","dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-08-23T03:04:59.000Z","updated_at":"2024-09-14T19:47:53.000Z","dependencies_parsed_at":"2023-10-01T18:52:51.885Z","dependency_job_id":"ce3ad8e4-c095-4f9e-9a23-ad789f6fbe63","html_url":"https://github.com/loggi/python-choicesenum","commit_stats":null,"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loggi%2Fpython-choicesenum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loggi%2Fpython-choicesenum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loggi%2Fpython-choicesenum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loggi%2Fpython-choicesenum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/loggi","download_url":"https://codeload.github.com/loggi/python-choicesenum/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247657281,"owners_count":20974345,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["choices","custom-fields","django","enum","python"],"created_at":"2024-07-31T22:01:48.072Z","updated_at":"2025-04-07T13:07:29.734Z","avatar_url":"https://github.com/loggi.png","language":"Python","readme":"============\nChoices Enum\n============\n\n\n.. image:: https://img.shields.io/pypi/v/choicesenum.svg\n        :target: https://pypi.python.org/pypi/choicesenum\n\n.. image:: https://travis-ci.org/loggi/python-choicesenum.svg?branch=master\n        :target: https://travis-ci.org/loggi/python-choicesenum\n\n.. image:: https://readthedocs.org/projects/python-choicesenum/badge/?version=latest\n        :target: https://python-choicesenum.readthedocs.io/en/latest/?badge=latest\n        :alt: Documentation Status\n\n.. image:: https://coveralls.io/repos/github/loggi/python-choicesenum/badge.svg?branch=master\n        :target: https://coveralls.io/github/loggi/python-choicesenum?branch=master\n\n\nPython's Enum with extra powers to play nice with labels and choices fields.\n\n* Free software: BSD license\n* Documentation: https://python-choicesenum.readthedocs.io.\n\n------------\nInstallation\n------------\n\nInstall ``choicesenum`` using pip::\n\n    $ pip install choicesenum\n\n--------\nFeatures\n--------\n\n* An ``ChoicesEnum`` that can be used to create constant groups.\n* ``ChoicesEnum`` can define labels to be used in `choices` fields.\n* Django fields included:  ``EnumCharField`` and ``EnumIntegerField``.\n* All ``ChoicesEnum`` types can be compared against their primitive values directly.\n* Support (tested) for Python 2.7, 3.5, 3.6, 3.7 and 3.8.\n* Support (tested) for Django 1.9, 1.10, 1.11, 2.0, 2.1, 2.2 and 3.0.\n\n--------------\nUsage examples\n--------------\n\nExample with ``HttpStatuses``:\n\n.. code:: python\n\n    class HttpStatuses(ChoicesEnum):\n        OK = 200\n        BAD_REQUEST = 400\n        UNAUTHORIZED = 401\n        FORBIDDEN = 403\n\nExample with ``Colors``:\n\n.. code:: python\n\n    from choicesenum import ChoicesEnum\n\n    class Colors(ChoicesEnum):\n        RED = '#f00', 'Vermelho'\n        GREEN = '#0f0', 'Verde'\n        BLUE = '#00f', 'Azul'\n\n\nComparison\n----------\n\nAll `Enum` types can be compared against their values:\n\n.. code:: python\n\n    assert HttpStatuses.OK == 200\n    assert HttpStatuses.BAD_REQUEST == 400\n    assert HttpStatuses.UNAUTHORIZED == 401\n    assert HttpStatuses.FORBIDDEN == 403\n\n    status_code = HttpStatuses.OK\n    assert 200 \u003c= status_code \u003c= 300\n\n    assert Colors.RED == '#f00'\n    assert Colors.GREEN == '#0f0'\n    assert Colors.BLUE == '#00f'\n\n\nLabel for free\n--------------\n\nAll `Enum` types have by default a `display` derived from the enum identifier:\n\n.. code:: python\n\n    assert HttpStatuses.OK.display == 'Ok'\n    assert HttpStatuses.BAD_REQUEST.display == 'Bad request'\n    assert HttpStatuses.UNAUTHORIZED.display == 'Unauthorized'\n    assert HttpStatuses.FORBIDDEN.display == 'Forbidden'\n\n\nYou can easily define your own custom display for an `Enum` item using a tuple:\n\n\n.. code:: python\n\n    class HttpStatuses(ChoicesEnum):\n        OK = 200, 'Everything is fine'\n        BAD_REQUEST = 400, 'You did a mistake'\n        UNAUTHORIZED = 401, 'I know your IP'\n        FORBIDDEN = 403\n\n    assert HttpStatuses.OK.display == 'Everything is fine'\n    assert HttpStatuses.BAD_REQUEST.display == 'You did a mistake'\n    assert HttpStatuses.UNAUTHORIZED.display == 'I know your IP'\n    assert HttpStatuses.FORBIDDEN.display == 'Forbidden'\n\n\nDynamic properties\n------------------\n\nFor each enum item, a dynamic property ``is_\u003cenum_item\u003e`` is generated to allow\nquick boolean checks:\n\n.. code:: python\n\n    color = Colors.RED\n    assert color.is_red\n    assert not color.is_blue\n    assert not color.is_green\n\nThis feature is usefull to avoid comparing a received enum value against a know enum item.\n\nFor example, you can replace code like this:\n\n.. code:: python\n\n    # status = HttpStatuses.BAD_REQUEST\n\n    def check_status(status):\n        if status == HttpStatuses.OK:\n            print(\"Ok!\")\n\nTo this:\n\n.. code:: python\n\n    def check_status(status):\n        if status.is_ok:\n            print(\"Ok!\")\n\n\nCustom methods and properties\n-----------------------------\n\nYou can declare custom properties and methods:\n\n.. code:: python\n\n    class HttpStatuses(ChoicesEnum):\n        OK = 200, 'Everything is fine'\n        BAD_REQUEST = 400, 'You did a mistake'\n        UNAUTHORIZED = 401, 'I know your IP'\n        FORBIDDEN = 403\n\n        @property\n        def is_error(self):\n            return self \u003e= self.BAD_REQUEST\n\n    assert HttpStatuses.OK.is_error is False\n    assert HttpStatuses.BAD_REQUEST.is_error is True\n    assert HttpStatuses.UNAUTHORIZED.is_error is True\n\nIteration\n---------\n\nThe enum type is iterable:\n\n.. code:: python\n\n    \u003e\u003e\u003e for color in Colors:\n    ...     print(repr(color))\n    Color('#f00').RED\n    Color('#0f0').GREEN\n    Color('#00f').BLUE\n\n\nOrder is guaranteed only for py3.4+. For fixed order in py2.7, you\ncan implement a magic attribute ``_order_``:\n\n.. code:: python\n\n    from choicesenum import ChoicesEnum\n\n    class Colors(ChoicesEnum):\n        _order_ = 'RED GREEN BLUE'\n\n        RED = '#f00', 'Vermelho'\n        GREEN = '#0f0', 'Verde'\n        BLUE = '#00f', 'Azul'\n\nChoices\n-------\n\nUse ``.choices()`` method to receive a list of tuples ``(item, display)``:\n\n.. code:: python\n\n    assert list(Colors.choices()) == [\n        ('#f00', 'Vermelho'),\n        ('#0f0', 'Verde'),\n        ('#00f', 'Azul'),\n    ]\n\nValues\n-------\n\nUse ``.values()`` method to receive a list of the inner values:\n\n.. code:: python\n\n    assert Colors.values() == ['#f00', '#0f0', '#00f', ]\n\nOptions\n-------\n\nEven if a ``ChoicesEnum`` class is an iterator by itself, you can use ``.options()`` to convert the enum items to a list:\n\n.. code:: python\n\n    assert Colors.options() == [Colors.RED, Colors.GREEN, Colors.BLUE]\n\nA \"dict like\" get\n-----------------\n\nUse ``.get(value, default=None)`` method to receive ``default`` if ``value`` is not an item of enum:\n\n.. code:: python\n\n    assert Colors.get(Colors.RED) == Colors.RED\n    assert Colors.get('#f00') == Colors.RED\n    assert Colors.get('undefined_color') is None\n    assert Colors.get('undefined_color', Colors.RED) == Colors.RED\n\nCompatibility\n-------------\n\nThe enum item can be used whenever the value is needed:\n\n.. code:: python\n\n    assert u'Currrent color is {c} ({c.display})'.format(c=color) ==\\\n           u'Currrent color is #f00 (Vermelho)'\n\nEven in dicts and sets, as it shares the same `hash()` from his value:\n\n.. code:: python\n\n    d = {\n        HttpStatuses.OK.value: \"using value\",\n        HttpStatuses.BAD_REQUEST: \"using enum\",\n        401: \"from original value\",\n    }\n    assert d[HttpStatuses.OK] == \"using value\"\n    assert d[HttpStatuses.BAD_REQUEST.value] == \"using enum\"\n    assert d[HttpStatuses.OK] == d[HttpStatuses.OK.value]\n    assert d[HttpStatuses.UNAUTHORIZED] == d[401]\n\nThere's also optimistic casting of inner types:\n\n.. code:: python\n\n    assert int(HttpStatuses.OK) == 200\n    assert float(HttpStatuses.OK) == 200.0\n    assert str(HttpStatuses.BAD_REQUEST) == \"400\"\n\n\nCheck membership:\n\n.. code:: python\n\n    assert HttpStatuses.OK in HttpStatuses\n    assert 200 in HttpStatuses\n    assert 999 not in HttpStatuses\n\n\nJSON\n....\n\nIf you want json serialization, you have at least two options:\n\n1. Patch the default serializer.\n2. Write a custom JSONEncoder.\n\nChoicesEnum comes with a handy patch funtion, you need to add this\ncode to somewhere at the top of everything to automagically add\njson serialization capabilities:\n\n.. code:: python\n\n    from choicesenum.patches import patch_json\n    patch_json()\n\n.. note::\n\n    Eventually ``__json__`` will be added to the stdlib, see\n    https://bugs.python.org/issue27362\n\n\n------\nDjango\n------\n\nFields\n------\n\nUsage with the custom Django fields:\n\n.. code:: python\n\n    from django.db import models\n    from choicesenum.django.fields import EnumCharField\n\n    class ColorModel(models.Model):\n        color = EnumCharField(\n            max_length=100,\n            enum=Colors,\n            default=Colors.GREEN,\n        )\n\n    instance = ColorModel()\n    assert instance.color ==  Colors.GREEN\n    assert instance.color.is_green is True\n    assert instance.color.value == Colors.GREEN.value == '#0f0'\n    assert instance.color.display == Colors.GREEN.display\n\n    instance.color = '#f00'\n    assert instance.color == '#f00'\n    assert instance.color.value == '#f00'\n    assert instance.color.display == 'Vermelho'\n\n\nIs guaranteed that the field value is *always* a `ChoicesEnum` item. Pay\nattention that the field will only accept valid values for the ``Enum`` in use,\nso if your field allow `null`, your enum should also:\n\n.. code:: python\n\n    from django.db import models\n    from choicesenum import ChoicesEnum\n    from choicesenum.django.fields import EnumIntegerField\n\n    class UserStatus(ChoicesEnum):\n        UNDEFINED = None\n        PENDING = 1\n        ACTIVE = 2\n        INACTIVE = 3\n        DELETED = 4\n\n\n    class User(models.Model):\n        status = EnumIntegerField(enum=UserStatus, null=True, )\n\n    instance = User()\n    assert instance.status.is_undefined is True\n    assert instance.status.value is None\n    assert instance.status == UserStatus.UNDEFINED\n    assert instance.status.display == 'Undefined'\n\n    # again...\n    instance.status = None\n    assert instance.status.is_undefined is True\n\n\n--------\nGraphene\n--------\n\nUsage with Graphene_ Enums:\n\n.. _Graphene: http://docs.graphene-python.org/en/latest/types/enums/#usage-with-python-enums\n\n.. code:: python\n\n    UserStatusEnum = graphene.Enum.from_enum(UserStatus)\n\n\n----------\nSchematics\n----------\n\nUsage with Schematics_ Enums:\n\n.. _Schematics: https://schematics.readthedocs.io/en/latest/usage/types.html\n\n.. code:: python\n\n    from schematics.models import Model as SchematicModel\n    from schematics.types import StringType, DateTimeType\n    from choicesenum import ChoicesEnum\n    from choicesenum.schematics.types import ChoicesEnumType\n\n    class HttpStatuses(ChoicesEnum):\n        OK = 200\n        BAD_REQUEST = 400\n        UNAUTHORIZED = 401\n        FORBIDDEN = 403\n\n    class CustomSchematicModel(SchematicModel):\n        name = StringType(required=True, max_length=255)\n        created = DateTimeType(required=True, formats=('%d/%m/%Y', ''))\n        http = ChoicesEnumType(HttpStatuses, required=True)\n","funding_links":[],"categories":["Python"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floggi%2Fpython-choicesenum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Floggi%2Fpython-choicesenum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floggi%2Fpython-choicesenum/lists"}