container field coercion

This commit is contained in:
protolambda 2019-06-18 02:18:00 +02:00
parent 73ba419d64
commit 8c6ddd5233
2 changed files with 25 additions and 1 deletions

View File

@ -1,4 +1,4 @@
from typing import Tuple, Dict, Iterator
from typing import Tuple, Iterator
from types import GeneratorType
@ -142,6 +142,16 @@ class Container(Series, metaclass=SSZType):
from .ssz_impl import signing_root
return signing_root(self)
def __setattr__(self, name, value):
if name not in self.__class__.__annotations__:
raise AttributeError("Cannot change non-existing SSZ-container attribute")
field_typ = self.__class__.__annotations__[name]
value = coerce_type_maybe(value, field_typ)
if not isinstance(value, field_typ):
raise ValueCheckError(f"Cannot set field of {self.__class__}:"
f" field: {name} type: {field_typ} value: {value} value type: {type(value)}")
super().__setattr__(name, value)
def get_field_values(self) -> Tuple[SSZValue, ...]:
cls = self.__class__
return tuple(getattr(self, field) for field in cls.get_field_names())

View File

@ -105,6 +105,20 @@ def test_container():
assert v.type().elem_type == uint8
assert v.type().length == 1024
y.a = 42
y.a = uint16(255)
try:
y.a = uint16(256)
assert False
except ValueError:
pass
try:
y.not_here = 5
assert False
except AttributeError:
pass
def test_list():
typ = List[uint64, 128]