Package: choicesenum
Python’s Enum with extra powers to play nice with labels and choices fields.Free software: BSD licenseDocumentation:https://python-choicesenum.readthedocs.io.InstallationInstallchoicesenumusing pip:$ pip install choicesenumFeaturesAnChoicesEnumthat can be used to create constant groups.ChoicesEnumcan define labels to be used inchoicesfields.Django fields included:EnumCharFieldandEnumIntegerField.AllChoicesEnumtypes can be compared against their primitive values directly.Support (tested) for Python 2.7, 3.5, 3.6, 3.7 and 3.8.Support (tested) for Django 1.9, 1.10, 1.11, 2.0, 2.1, 2.2 and 3.0.Usage examplesExample withHttpStatuses:classHttpStatuses(ChoicesEnum):OK=200BAD_REQUEST=400UNAUTHORIZED=401FORBIDDEN=403Example withColors:fromchoicesenumimportChoicesEnumclassColors(ChoicesEnum):RED='#f00','Vermelho'GREEN='#0f0','Verde'BLUE='#00f','Azul'ComparisonAllEnumtypes can be compared against their values:assertHttpStatuses.OK==200assertHttpStatuses.BAD_REQUEST==400assertHttpStatuses.UNAUTHORIZED==401assertHttpStatuses.FORBIDDEN==403status_code=HttpStatuses.OKassert200<=status_code<=300assertColors.RED=='#f00'assertColors.GREEN=='#0f0'assertColors.BLUE=='#00f'Label for freeAllEnumtypes have by default adisplayderived from the enum identifier:assertHttpStatuses.OK.display=='Ok'assertHttpStatuses.BAD_REQUEST.display=='Bad request'assertHttpStatuses.UNAUTHORIZED.display=='Unauthorized'assertHttpStatuses.FORBIDDEN.display=='Forbidden'You can easily define your own custom display for anEnumitem using a tuple:classHttpStatuses(ChoicesEnum):OK=200,'Everything is fine'BAD_REQUEST=400,'You did a mistake'UNAUTHORIZED=401,'I know your IP'FORBIDDEN=403assertHttpStatuses.OK.display=='Everything is fine'assertHttpStatuses.BAD_REQUEST.display=='You did a mistake'assertHttpStatuses.UNAUTHORIZED.display=='I know your IP'assertHttpStatuses.FORBIDDEN.display=='Forbidden'Dynamic propertiesFor each enum item, a dynamic propertyis_<enum_item>is generated to allow
quick boolean checks:color=Colors.REDassertcolor.is_redassertnotcolor.is_blueassertnotcolor.is_greenThis feature is usefull to avoid comparing a received enum value against a know enum item.For example, you can replace code like this:# status = HttpStatuses.BAD_REQUESTdefcheck_status(status):ifstatus==HttpStatuses.OK:print("Ok!")To this:defcheck_status(status):ifstatus.is_ok:print("Ok!")Custom methods and propertiesYou can declare custom properties and methods:classHttpStatuses(ChoicesEnum):OK=200,'Everything is fine'BAD_REQUEST=400,'You did a mistake'UNAUTHORIZED=401,'I know your IP'FORBIDDEN=403@propertydefis_error(self):returnself>=self.BAD_REQUESTassertHttpStatuses.OK.is_errorisFalseassertHttpStatuses.BAD_REQUEST.is_errorisTrueassertHttpStatuses.UNAUTHORIZED.is_errorisTrueIterationThe enum type is iterable:>>>forcolorinColors:...print(repr(color))Color('#f00').REDColor('#0f0').GREENColor('#00f').BLUEOrder is guaranteed only for py3.4+. For fixed order in py2.7, you
can implement a magic attribute_order_:fromchoicesenumimportChoicesEnumclassColors(ChoicesEnum):_order_='RED GREEN BLUE'RED='#f00','Vermelho'GREEN='#0f0','Verde'BLUE='#00f','Azul'ChoicesUse.choices()method to receive a list of tuples(item, display):assertlist(Colors.choices())==[('#f00','Vermelho'),('#0f0','Verde'),('#00f','Azul'),]ValuesUse.values()method to receive a list of the inner values:assertColors.values()==['#f00','#0f0','#00f',]OptionsEven if aChoicesEnumclass is an iterator by itself, you can use.options()to convert the enum items to a list:assertColors.options()==[Colors.RED,Colors.GREEN,Colors.BLUE]A “dict like” getUse.get(value, default=None)method to receivedefaultifvalueis not an item of enum:assertColors.get(Colors.RED)==Colors.REDassertColors.get('#f00')==Colors.REDassertColors.get('undefined_color')isNoneassertColors.get('undefined_color',Colors.RED)==Colors.REDCompatibilityThe enum item can be used whenever the value is needed:assertu'Currrent color is{c}({c.display})'.format(c=color)==\u'Currrent color is #f00 (Vermelho)'Even in dicts and sets, as it shares the samehash()from his value:d={HttpStatuses.OK.value:"using value",HttpStatuses.BAD_REQUEST:"using enum",401:"from original value",}assertd[HttpStatuses.OK]=="using value"assertd[HttpStatuses.BAD_REQUEST.value]=="using enum"assertd[HttpStatuses.OK]==d[HttpStatuses.OK.value]assertd[HttpStatuses.UNAUTHORIZED]==d[401]There’s also optimistic casting of inner types:assertint(HttpStatuses.OK)==200assertfloat(HttpStatuses.OK)==200.0assertstr(HttpStatuses.BAD_REQUEST)=="400"Check membership:assertHttpStatuses.OKinHttpStatusesassert200inHttpStatusesassert999notinHttpStatusesJSONIf you want json serialization, you have at least two options:Patch the default serializer.Write a custom JSONEncoder.ChoicesEnum comes with a handy patch funtion, you need to add this
code to somewhere at the top of everything to automagically add
json serialization capabilities:fromchoicesenum.patchesimportpatch_jsonpatch_json()NoteEventually__json__will be added to the stdlib, seehttps://bugs.python.org/issue27362DjangoFieldsUsage with the custom Django fields:fromdjango.dbimportmodelsfromchoicesenum.django.fieldsimportEnumCharFieldclassColorModel(models.Model):color=EnumCharField(max_length=100,enum=Colors,default=Colors.GREEN,)instance=ColorModel()assertinstance.color==Colors.GREENassertinstance.color.is_greenisTrueassertinstance.color.value==Colors.GREEN.value=='#0f0'assertinstance.color.display==Colors.GREEN.displayinstance.color='#f00'assertinstance.color=='#f00'assertinstance.color.value=='#f00'assertinstance.color.display=='Vermelho'Is guaranteed that the field value isalwaysaChoicesEnumitem. Pay
attention that the field will only accept valid values for theEnumin use,
so if your field allownull, your enum should also:fromdjango.dbimportmodelsfromchoicesenumimportChoicesEnumfromchoicesenum.django.fieldsimportEnumIntegerFieldclassUserStatus(ChoicesEnum):UNDEFINED=NonePENDING=1ACTIVE=2INACTIVE=3DELETED=4classUser(models.Model):status=EnumIntegerField(enum=UserStatus,null=True,)instance=User()assertinstance.status.is_undefinedisTrueassertinstance.status.valueisNoneassertinstance.status==UserStatus.UNDEFINEDassertinstance.status.display=='Undefined'# again...instance.status=Noneassertinstance.status.is_undefinedisTrueGrapheneUsage withGrapheneEnums:UserStatusEnum=graphene.Enum.from_enum(UserStatus)SchematicsUsage withSchematicsEnums:fromschematics.modelsimportModelasSchematicModelfromschematics.typesimportStringType,DateTimeTypefromchoicesenumimportChoicesEnumfromchoicesenum.schematics.typesimportChoicesEnumTypeclassHttpStatus(ChoicesEnum):OK=200BAD_REQUEST=400UNAUTHORIZED=401FORBIDDEN=403classCustomSchematicModel(SchematicModel):name=StringType(required=True,max_length=255)created=DateTimeType(required=True,formats=('%d/%m/%Y',''))http=ChoicesEnumType(HttpStatuses,required=True)History0.7.0 (2020-08-02)Add support Django 3.0 (tks @klette).Drop support for Python 3.4.Fix issue when using Django EnumIntegerField on Admin.0.6.0 (2019-09-05)Adding schematics contrib type ChoicesEnumType.Drop support for Django 1.6, 1.7, 1.8.0.5.3 (2019-02-06)Fix Django migrations with default values for Django 1.7+.0.5.2 (2019-01-18)Optimize member check and dynamic creation ofis_<name>properties.0.5.1 (2019-01-04)Fix readme RST (requires new Pypi upload).0.5.0 (2019-01-04)Membership test (item in Enum) returning valid results for primitive values.New dict-like.getmethod able to return a default value (thanks @leandrogs).Django: Support Postgres array functions and queries (thanks @tomfa).Django: Support for deferring an enum field usingqueryset.defer()(thanks @noamkush).Django: 2.1 support.0.4.0 (2018-07-13)Optimistic casting of inner types (thanks @gabisurita).Optional stdlib patch to automagic json serialization support.Add Python3.7 to the test matrix.0.3.0 (2018-06-22)Official Django 2.0 support (0.2.2 just works fine too).ChoicesEnumsharing the same hash() as his value. Can be used to retrieve/restore items in dicts (d[enum] == d[enum.value]).0.2.2 (2017-12-01)Fix: Support queries throughselect_relatedwith noNonevalue defined (thanks @klette).0.2.1 (2017-09-30)Fix South migrations for Django 1.6.0.2.0 (2017-09-11)ChoicesEnumitems are comparable by their values (==, !=, >, >=, <, <=) (thanks @jodal).+``ChoicesEnum.values``: Returns all the Enum’s raw values (eq:[x.value for x in Enum]).0.1.7 (2017-09-10)Fix:ChoicesEnumis now hashable (thanks @jodal).0.1.6 (2017-09-08)Fix: Proxy__len__calls to the inner enum value.0.1.5 (2017-09-05)+ChoicesEnum.description: Alias forlabel, allow enum descriptors to be used by Graphene.0.1.4 (2017-08-28)Fix South migrations for Django 1.6.ChoicesEnumrepr can be used to reconstruct an instance (item == eval(repr(item))).0.1.3 (2017-08-28)Fix sdist not including sub-modules (django contrib).0.1.2 (2017-08-27)README fixes and improvements.0.1.0 (2017-08-27)First release on PyPI.