Skip to content

Commit

Permalink
Merge pull request #19 from joakim-hove/enum-from-name
Browse files Browse the repository at this point in the history
Added functionality to get an enum from the name.
  • Loading branch information
joakim-hove authored Feb 24, 2018
2 parents a0e01d8 + cc7ed45 commit db9432c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions cwrap/basecenum.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ def from_param(cls, c_class_object):
raise ValueError("c_class_object must be an BaseCEnum instance!")
return c_class_object.value

@classmethod
def from_string(cls, name):
for enum in cls.enum_namespace[cls]:
if enum.name == name:
return enum

raise ValueError("No such enum:%s" % name)

@classmethod
def addEnum(cls, name, value):
name = str(name)
Expand Down
14 changes: 14 additions & 0 deletions tests/test_basecenum.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,17 @@ class MyLonelyEnum(BaseCEnum):
self.assertEqual(str(tri), 'THREE')
self.assertEqual(tri.name, 'THREE')
self.assertEqual(tri.value, 3)


def test_from_name(self):
class EnumName(BaseCEnum):
pass

EnumName.addEnum("ONE", 1)
EnumName.addEnum("TWO", 2)

with self.assertRaises(ValueError):
enum = EnumName.from_string("No-not-this")

one = EnumName.from_string("ONE")
self.assertEqual(one, EnumName.ONE)

0 comments on commit db9432c

Please sign in to comment.