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

Auto apply dataclass decorator to subclasses #30

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
7 changes: 5 additions & 2 deletions coqpit/coqpit.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ def deserialize(self, data: dict) -> "Serializable":
init_kwargs[field.name] = value
continue
if value == MISSING:
raise ValueError("deserialized with unknown value for {} in {}".format(field.name, self.__name__))
raise ValueError(f"deserialized with unknown value for {field.name} in {self.__name__}")
value = _deserialize(value, field.type)
init_kwargs[field.name] = value
for k, v in init_kwargs.items():
Expand Down Expand Up @@ -438,7 +438,7 @@ def deserialize_immutable(cls, data: dict) -> "Serializable":
init_kwargs[field.name] = value
continue
if value == MISSING:
raise ValueError("Deserialized with unknown value for {} in {}".format(field.name, cls.__name__))
raise ValueError(f"Deserialized with unknown value for {field.name} in {cls.__name__}")
value = _deserialize(value, field.type)
init_kwargs[field.name] = value
return cls(**init_kwargs)
Expand Down Expand Up @@ -578,6 +578,9 @@ class Coqpit(Serializable, MutableMapping):

_initialized = False

def __init_subclass__(cls, **kwargs):
return dataclass(_cls=cls, **kwargs)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if the class already has the annotation? Otherwise LGTM.


def _is_initialized(self):
"""Check if Coqpit is initialized. Useful to prevent running some aux functions
at the initialization when no attribute has been defined."""
Expand Down
10 changes: 10 additions & 0 deletions tests/test_metaing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import dataclasses
from coqpit.coqpit import Coqpit


class SimpleConstructConfig(Coqpit):
a: int = 20


def test_copying():
assert dataclasses.is_dataclass(SimpleConstructConfig())