Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UseEnum does not work with str enum #827

Open
maxnoe opened this issue Jan 20, 2023 · 0 comments
Open

UseEnum does not work with str enum #827

maxnoe opened this issue Jan 20, 2023 · 0 comments

Comments

@maxnoe
Copy link
Contributor

maxnoe commented Jan 20, 2023

Slightly adapting the UseEnum example to use a str based enum makes it fail to recognize the enum by the value:

import enum
from traitlets import HasTraits, UseEnum

class Color(str, enum.Enum):
    RED = "red"
    BLUE = "blue"
    GREEN = "green"

class MyEntity(HasTraits):
    color = UseEnum(Color, default_value=Color.BLUE)

entity = MyEntity(color=Color.RED)
entity.color = Color.GREEN
entity.color = "GREEN"  
entity.color = "Color.GREEN"  
entity.color = "green"
assert entity.color is Color.GREEN

Raises:

❯ python test_enum.py
Traceback (most recent call last):
  File "/home/mnoethe/Projects/test_enum.py", line 16, in <module>
    entity.color = "green"              # USE: number (as int)
  File "/home/mnoethe/.local/conda/envs/cta-dev/lib/python3.9/site-packages/traitlets/traitlets.py", line 729, in __set__
    self.set(obj, value)
  File "/home/mnoethe/.local/conda/envs/cta-dev/lib/python3.9/site-packages/traitlets/traitlets.py", line 703, in set
    new_value = self._validate(obj, value)
  File "/home/mnoethe/.local/conda/envs/cta-dev/lib/python3.9/site-packages/traitlets/traitlets.py", line 735, in _validate
    value = self.validate(obj, value)
  File "/home/mnoethe/.local/conda/envs/cta-dev/lib/python3.9/site-packages/traitlets/traitlets.py", line 3582, in validate
    self.error(obj, value)
  File "/home/mnoethe/.local/conda/envs/cta-dev/lib/python3.9/site-packages/traitlets/traitlets.py", line 841, in error
    raise TraitError(e)
traitlets.traitlets.TraitError: The 'color' trait of a MyEntity instance expected any of ['RED', 'BLUE', 'GREEN'], not the str 'green'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant