Implement RFC 22: Add ValueCastable.shape().

Fixes #794.
Closes #876.
This commit is contained in:
Catherine 2023-08-23 07:48:33 +00:00
parent 7714ce329a
commit f95fe45186
5 changed files with 67 additions and 33 deletions

View file

@ -1110,7 +1110,11 @@ class Signal(Value, DUID, metaclass=_SignalMeta):
new_name = other.name + str(name_suffix)
else:
new_name = tracer.get_var_name(depth=2 + src_loc_at, default="$like")
kw = dict(shape=Value.cast(other).shape(), name=new_name)
if isinstance(other, ValueCastable):
shape = other.shape()
else:
shape = Value.cast(other).shape()
kw = dict(shape=shape, name=new_name)
if isinstance(other, Signal):
kw.update(reset=other.reset, reset_less=other.reset_less,
attrs=other.attrs, decoder=other.decoder)
@ -1363,6 +1367,9 @@ class ValueCastable:
if not hasattr(cls, "as_value"):
raise TypeError(f"Class '{cls.__name__}' deriving from `ValueCastable` must override "
"the `as_value` method")
if not hasattr(cls, "shape"):
raise TypeError(f"Class '{cls.__name__}' deriving from `ValueCastable` must override "
"the `shape` method")
if not hasattr(cls.as_value, "_ValueCastable__memoized"):
raise TypeError(f"Class '{cls.__name__}' deriving from `ValueCastable` must decorate "
"the `as_value` method with the `ValueCastable.lowermethod` decorator")

View file

@ -115,20 +115,6 @@ class Layout(ShapeCastable, metaclass=ABCMeta):
raise TypeError("Object {!r} cannot be converted to a data layout"
.format(obj))
@staticmethod
def of(obj):
"""Extract the layout that was used to create a view.
Raises
------
TypeError
If ``obj`` is not a :class:`View` instance.
"""
if not isinstance(obj, View):
raise TypeError("Object {!r} is not a data view"
.format(obj))
return obj._View__orig_layout
@abstractmethod
def __iter__(self):
"""Iterate fields in the layout.
@ -611,6 +597,16 @@ class View(ValueCastable):
self.__layout = cast_layout
self.__target = cast_target
def shape(self):
"""Get layout of this view.
Returns
-------
:class:`Layout`
The ``layout`` provided when constructing the view.
"""
return self.__orig_layout
@ValueCastable.lowermethod
def as_value(self):
"""Get underlying value.