Skip to content

Commit

Permalink
wip: python: Allow assignment of enum fields from enums with same name
Browse files Browse the repository at this point in the history
  • Loading branch information
shramov committed Oct 24, 2023
1 parent 8956074 commit dcd634e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
11 changes: 11 additions & 0 deletions python/test/test_scheme.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import copy
import datetime
import decimal
import enum
import pytest
import struct

Expand Down Expand Up @@ -658,6 +659,16 @@ def test_enum():
assert m.SCHEME['e8'].from_string('1') == m.e8.A
assert m.SCHEME['e8'].from_string('A') == m.e8.A

class e8(enum.Enum):
A = 1
B = 2
Other = 30

with pytest.raises(ValueError): m.e64 = e8.A
with pytest.raises(ValueError): m.e8 = e8.Other
m.e8 = e8.A
assert m.e8.name == 'A'

def test_enum_eq():
SCHEME = """yamls://
- enums:
Expand Down
6 changes: 6 additions & 0 deletions python/tll/scheme.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,12 @@ cdef class FEnum(FBase):
cdef convert(FEnum self, v):
if isinstance(v, str):
return self.enum_class.__members__[v]
elif isinstance(v, enum.Enum):
if isinstance(v, self.enum_class):
return v
if self.enum_class.__name__ != v.__class__.__name__:
raise ValueError(f"Enum name of '{v}' does not match field enum name '{self.enum_class.__name__}'")
return self.enum_class(v.value)
return self.enum_class(v)
cdef from_string(FEnum self, str s):
v = self.enum_class.__members__.get(s, None)
Expand Down

0 comments on commit dcd634e

Please sign in to comment.