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

Add a skip_missing kwarg to the as_ methods of Struct objects #954

Merged
merged 1 commit into from
Apr 8, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions tests/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,3 +774,15 @@ class TestStruct(t.Struct):
s1 = TestStruct(foo=1, bar=2, baz="asd")

assert repr(s1) == "TestStruct(foo=2, bar=bar, baz=baz)"


def test_skip_missing():
class TestStruct(t.Struct):
foo: t.uint8_t
bar: t.uint16_t

assert TestStruct(foo=1).as_dict() == {"foo": 1, "bar": None}
assert TestStruct(foo=1).as_dict(skip_missing=True) == {"foo": 1}

assert TestStruct(foo=1).as_tuple() == (1, None)
assert TestStruct(foo=1).as_tuple(skip_missing=True) == (1,)
18 changes: 14 additions & 4 deletions zigpy/types/struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,11 +184,21 @@ def assigned_fields(self, *, strict=False) -> list[tuple[StructField, typing.Any

return assigned_fields

def as_dict(self) -> dict[str, typing.Any]:
return {f.name: getattr(self, f.name) for f in self.fields}
def as_dict(self, *, skip_missing: bool = False) -> dict[str, typing.Any]:
d = {}

def as_tuple(self) -> tuple:
return tuple(getattr(self, f.name) for f in self.fields)
for f in self.fields:
value = getattr(self, f.name)

if value is None and skip_missing:
continue

d[f.name] = value

return d

def as_tuple(self, *, skip_missing: bool = False) -> tuple:
return tuple(self.as_dict(skip_missing=skip_missing).values())

def serialize(self) -> bytes:
chunks = []
Expand Down