Skip to content

Commit

Permalink
Merge pull request #9 from eladrich/feat/enum
Browse files Browse the repository at this point in the history
Changed enum parsing mechanism to be name based 💱
  • Loading branch information
eladrich authored Feb 10, 2022
2 parents 4204d4f + 956df74 commit 25fdce1
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 15 deletions.
7 changes: 4 additions & 3 deletions pyrallis/parsers/decoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
is_tuple,
is_union,
is_enum,
ParsingError
ParsingError,
format_error
)

logger = getLogger(__name__)
Expand Down Expand Up @@ -67,7 +68,7 @@ def decode_dataclass(
raise e
except Exception as e:
raise ParsingError(
f"Failed when parsing value='{raw_value}' into field \"{cls}.{name}\" of type {field.type}.\n\tUnderlying error: {e}")
f"Failed when parsing value='{raw_value}' into field \"{cls}.{name}\" of type {field.type}.\n\tUnderlying error is \"{format_error(e)}\"")

if field.init:
init_args[name] = field_value
Expand Down Expand Up @@ -163,7 +164,7 @@ def get_decoding_fn(t: Type[T]) -> Callable[[Any], T]:
return decode_union(*args)

elif is_enum(t):
return t
return lambda key: t[key]

import typing_inspect as tpi

Expand Down
2 changes: 1 addition & 1 deletion pyrallis/parsers/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def encode_dict(obj: Mapping) -> Dict[Any, Any]:

@encode.register(Enum)
def encode_enum(obj: Enum) -> str:
return obj.value
return obj.name


for t in [str, float, int, bool, bytes]:
Expand Down
7 changes: 7 additions & 0 deletions pyrallis/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,13 @@ def remove_matching(dict_a, dict_b):
return deflatten(dict_a)


def format_error(e: Exception):
try:
return f'{type(e).__name__}: {e}'
except Exception:
return f'Exception: {e}'


CONFIG_ARG = 'config_path'

if __name__ == "__main__":
Expand Down
10 changes: 5 additions & 5 deletions tests/test_choice.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
from builtins import TypeError
from dataclasses import dataclass, field
from enum import Enum
from enum import Enum, auto

from tests.testutils import *


class Color(Enum):
blue: str = "blue"
red: str = "red"
green: str = "green"
orange: str = "orange"
blue: str = auto()
red: str = auto()
green: str = auto()
orange: str = auto()


def test_passing_enum_to_choice():
Expand Down
28 changes: 22 additions & 6 deletions tests/test_decoding.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
from dataclasses import dataclass, field
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
from enum import Enum, auto

from pyrallis.utils import PyrallisException

import pyrallis
from .testutils import *


class Color(Enum):
blue: str = auto()
red: str = auto()


def test_encode_something(simple_attribute):
some_type, passed_value, expected_value = simple_attribute
some_type, _, expected_value = simple_attribute

@dataclass
class SomeClass:
Expand All @@ -26,7 +28,7 @@ class SomeClass:


def test_dump_load(simple_attribute, tmp_path):
some_type, passed_value, expected_value = simple_attribute
some_type, _, expected_value = simple_attribute

@dataclass
class SomeClass:
Expand All @@ -49,6 +51,19 @@ class SomeClass:
assert new_b == b


def test_dump_load_enum(tmp_path):
@dataclass
class SomeClass:
color: Color = Color.red

b = SomeClass()
tmp_file = tmp_path / 'config.yaml'
pyrallis.dump(b, tmp_file.open('w'))

new_b = pyrallis.parse(config_class=SomeClass, config_path=tmp_file, args="")
assert new_b == b


def test_reserved_config_word():
@dataclass
class MainClass:
Expand All @@ -57,6 +72,7 @@ class MainClass:
with raises(PyrallisException):
pyrallis.parse(MainClass)


def test_super_nesting():
@dataclass
class Complicated:
Expand Down

0 comments on commit 25fdce1

Please sign in to comment.