-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Export the collections extension (#1506)
#1450 embedded the standard extension definitions in hugr-py, including `collections`, but it didn't add a way to load it as it did with all the others. This PR adds a `hugr.std.collections` module that just loads the bundled json. drive-by: Implement `__str__` for `FloatVal` and `IntVal`
- Loading branch information
Showing
3 changed files
with
48 additions
and
0 deletions.
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 |
---|---|---|
@@ -0,0 +1,40 @@ | ||
"""Collection types and operations.""" | ||
|
||
from __future__ import annotations | ||
|
||
from dataclasses import dataclass | ||
|
||
import hugr.tys as tys | ||
from hugr import val | ||
from hugr.std import _load_extension | ||
from hugr.utils import comma_sep_str | ||
|
||
EXTENSION = _load_extension("collections") | ||
|
||
|
||
def list_type(ty: tys.Type) -> tys.ExtType: | ||
"""Returns a list type with a fixed element type.""" | ||
arg = tys.TypeTypeArg(ty) | ||
return EXTENSION.types["List"].instantiate([arg]) | ||
|
||
|
||
@dataclass | ||
class ListVal(val.ExtensionValue): | ||
"""Constant value for a list of elements.""" | ||
|
||
v: list[val.Value] | ||
ty: tys.Type | ||
|
||
def __init__(self, v: list[val.Value], elem_ty: tys.Type) -> None: | ||
self.v = v | ||
self.ty = list_type(elem_ty) | ||
|
||
def to_value(self) -> val.Extension: | ||
name = "ListValue" | ||
# The value list must be serialized at this point, otherwise the | ||
# `Extension` value would not be serializable. | ||
vs = [v._to_serial_root() for v in self.v] | ||
return val.Extension(name, typ=self.ty, val=vs, extensions=[EXTENSION.name]) | ||
|
||
def __str__(self) -> str: | ||
return f"[{comma_sep_str(self.v)}]" |
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
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