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

Revive ValueEnum.as_dict method #974

Merged
merged 2 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading