aenum icon indicating copy to clipboard operation
aenum copied to clipboard

Allow creating NoAlias enums from enum members

Open erik-hasse opened this issue 3 years ago • 0 comments

Allow something like this: MyNoAliasEnum(MyNoAliasEnum.FOO). It makes sense why NoAlias enums can't be looked up by the raw value since they may not be unique, but unless I'm missing something I don't see a reason they couldn't be looked up by actual enum members. It should be as simple as switching these two if blocks: https://github.com/ethanfurman/aenum/blob/master/aenum/init.py#L3059-L3064 If there are no objections I could definitely open a PR with this change.

Motivation

Currently NoAlias enums are unusable with Pydantic as demonstrated in this example:

from aenum import NoAliasEnum
from pydantic import BaseModel

class MyEnum(NoAliasEnum):
    FOO = 1
    BAR = 1

class MyModel(BaseModel):
    val: MyEnum

MyModel(val=MyEnum.FOO)

which raises the following error:

ValidationError                           Traceback (most recent call last)
Cell In [104], line 1
----> 1 MyModel(val=MyEnum.FOO)

File ~/.pyenv/versions/3.8.13/envs/multistep-forecaster/lib/python3.8/site-packages/pydantic/main.py:341, in pydantic.main.BaseModel.__init__()

ValidationError: 1 validation error for MyModel
val
  NoAlias enumerations cannot be looked up by value (type=type_error)

This is because Pydantic automatically calls MyEnum(input_val) regardless of the actual type of input_val.

erik-hasse avatar Oct 04 '22 14:10 erik-hasse