-
Notifications
You must be signed in to change notification settings - Fork 3
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
WIP: Dataclass #31
Merged
WIP: Dataclass #31
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
8e1afc7
Initial dataclass chekin.
HeMan 77fced9
First somewhat working version of dataclass.
HeMan 0cadc31
Move dataclass creation to binmapdataclass.
HeMan b1f5aef
Make pading behave.
HeMan d32ee75
Make constants work
HeMan 269ac31
Added all data types.
HeMan 26d13fc
Added some typing.
HeMan 7d7d27f
Add support for enums
HeMan 9368dc6
Updated documentation.
HeMan 7d60a73
Make black and isort be friends.
HeMan 41cffd4
Put types in own file.
HeMan bdb2df9
Make README render
JimmyHedman ca8a847
Make binmapdataclass an implicit dataclass.
HeMan 1d2d109
Make types an explicit import.
HeMan 38b856a
Removed unused attributes.
HeMan ea7d5e0
Remove ABC
HeMan 761f587
Only need inheritance
JimmyHedman f138a53
Simplified and moved some intialisations.
HeMan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
import dataclasses | ||
import struct | ||
from abc import ABC | ||
from enum import Enum | ||
from typing import Dict, NewType, Tuple, Type, TypeVar, Union, get_type_hints | ||
|
||
T = TypeVar("T") | ||
|
@@ -28,7 +29,6 @@ def __get__(self, obj, owner): | |
def __set__(self, obj, value): | ||
type_hints = get_type_hints(obj) | ||
struct.pack(datatypemapping[type_hints[self.name]][1], value) | ||
# struct.pack(obj._datafields[self.name], value) | ||
obj.__dict__[self.name] = value | ||
|
||
|
||
|
@@ -44,25 +44,18 @@ def __set__(self, obj, value): | |
pass | ||
|
||
|
||
class EnumField(BaseDescriptor): | ||
class EnumField(BinField): | ||
"""EnumField descriptor uses "enum" to map to and from strings. Accepts | ||
both strings and values when setting. Only values that has a corresponding | ||
string is allowed.""" | ||
|
||
def __get__(self, obj, owner): | ||
value = obj.__dict__[f"_{self.name}"] | ||
return obj._enums[self.name][value] | ||
|
||
def __set__(self, obj, value): | ||
if value in obj._enums[self.name]: | ||
obj.__dict__[f"_{self.name}"] = value | ||
datafieldsmap = {f.name: f for f in dataclasses.fields(obj)} | ||
if type(value) is str: | ||
datafieldsmap[self.name].metadata["enum"][value] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is this a dictionary access? I'd leave a comment explaining this if its supposed to be here. |
||
else: | ||
for k, v in obj._enums[self.name].items(): | ||
if v == value: | ||
obj.__dict__[f"_{self.name}"] = k | ||
return | ||
|
||
raise ValueError("Unknown enum or value") | ||
datafieldsmap[self.name].metadata["enum"](value) | ||
obj.__dict__[self.name] = value | ||
|
||
|
||
class ConstField(BinField): | ||
|
@@ -130,6 +123,8 @@ def binmapdataclass(cls: Type[T]) -> Type[T]: | |
_base, _type = datatypemapping[type_hints[field_.name]] | ||
if "constant" in field_.metadata: | ||
_base = ConstField | ||
elif "enum" in field_.metadata: | ||
_base = EnumField | ||
setattr(cls, field_.name, _base(name=field_.name)) | ||
if type_hints[field_.name] is pad: | ||
_type = field_.default * _type | ||
|
@@ -153,15 +148,19 @@ def constant(value: Union[int, float, str]) -> dataclasses.Field: | |
|
||
|
||
def stringfield( | ||
length: int = 1, default: str = "", fillchar: str = " " | ||
length: int = 1, default: bytes = b"", fillchar: bytes = b" " | ||
) -> dataclasses.Field: | ||
if default == "": | ||
_default = "\x00" * length | ||
if default == b"": | ||
_default = b"\x00" * length | ||
else: | ||
_default = f"{default:{fillchar}<{length}}" | ||
_default = bytes(f"{default:{fillchar}<{length}}") | ||
return dataclasses.field(default=_default, metadata={"length": length}) | ||
|
||
|
||
def enumfield(enumclass: Enum, default: Enum = None) -> dataclasses.Field: | ||
return dataclasses.field(default=default, metadata={"enum": enumclass}) | ||
|
||
|
||
@dataclasses.dataclass | ||
class BinmapDataclass(ABC): | ||
_byteorder = "" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if isinstance(value, str):
This allows subtypes which may be relevant here.