Skip to content

Commit

Permalink
Revive ValueEnum.as_dict method (#974)
Browse files Browse the repository at this point in the history
* Revive ValueEnum.as_dict method

* linting
  • Loading branch information
esoteric-ephemera authored Apr 3, 2024
1 parent 78a0ecd commit 98debc2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
12 changes: 11 additions & 1 deletion emmet-core/emmet/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,13 @@ def jsanitize(obj, strict=False, allow_bson=False):

class ValueEnum(Enum):
"""
Enum that serializes to string as the value
Enum that serializes to string as the value.
While this method has an `as_dict` method, this
returns a `str`. This is to ensure deserialization
to a `str` when functions like `monty.json.jsanitize`
are called on a ValueEnum with `strict = True` and
`enum_values = False` (occurs often in jobflow).
"""

def __str__(self):
Expand All @@ -304,6 +310,10 @@ def __hash__(self):
"""Get a hash of the enum."""
return hash(str(self))

def as_dict(self) -> str:
"""Deserialize in a kludgey way."""
return self.__str__()


class DocEnum(ValueEnum):
"""
Expand Down
5 changes: 5 additions & 0 deletions emmet-core/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,14 @@ class TempEnum(ValueEnum):

assert str(TempEnum.A) == "A"
assert str(TempEnum.B) == "B"

dumpfn(TempEnum, tmp_path / "temp.json")
assert Path(tmp_path, "temp.json").is_file()

# ensure that as_dict method yields str
assert hasattr(TempEnum, "as_dict")
assert all(isinstance(val.as_dict(), str) for val in TempEnum)


def test_doc_enum():
class TestEnum(DocEnum):
Expand Down

0 comments on commit 98debc2

Please sign in to comment.