Skip to content

Commit

Permalink
Improve K-Class to accept list of K-Class prop
Browse files Browse the repository at this point in the history
Signed-off-by: Sunghyun Hwang <me@sunghyunzz.com>

#5
  • Loading branch information
0xd669 committed Sep 10, 2018
1 parent 4373d3e commit f33d2df
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
6 changes: 6 additions & 0 deletions kformat/kclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ def init(self, *args):
assert isinstance(v, prop), \
f'{type(v).__name__} is not type of {prop.__name__}'
prop_bytes.append(prop.bytes)
elif hasattr(prop, '__origin__') and prop.__origin__ == list:
assert isinstance(v, list), f'{type(v).__name__} is not List'
assert all(
getattr(item, KCLASS_ANNOTATION, False) for item in v
), f'All of list items should be type of K-Class'
prop_bytes.extend(c.bytes for c in v)
else:
assert isinstance(prop, kproperty.KProperty), \
f'{prop.__name__} is not subtype of KProperty'
Expand Down
8 changes: 6 additions & 2 deletions tests/test_kclass.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import unittest
from typing import List

from kformat.kclass import kclass
from kformat.kproperty import AN, N
Expand All @@ -18,12 +19,14 @@ class Something:
n: N(10)
an: AN(20)
other: Other
others: List[Other]
filler: AN(100)

sth = Something(
123,
'k-class',
Other(456, 'subclass'),
[],
None
)
self.assertIsNotNone(sth)
Expand All @@ -42,11 +45,12 @@ class Something:
a: N(10)
b: AN(20)
other: Other
others: List[Other]
c: N(5)
d: AN(10)

sth = Something(1, 2, Other(3, 4), 5, 6)
self.assertEqual(sth.bytes, b'NANANNNAN')
sth = Something(1, 2, Other(3, 4), [Other(1, 1), Other(1, 1)], 5, 6)
self.assertEqual(sth.bytes, b'NANANNANNANNNAN')

# Reset to_bytes funcs to default
N.to_bytes = _n
Expand Down

0 comments on commit f33d2df

Please sign in to comment.