Skip to content

Commit 0547665

Browse files
Construct machine-sized typed clasical variables (#90)
* add method to construct machine-sized typed vars * fix broken test
1 parent 8b6319a commit 0547665

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

oqpy/classical_types.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import functools
2121
import random
2222
import string
23+
import sys
2324
from typing import (
2425
TYPE_CHECKING,
2526
Any,
@@ -50,6 +51,11 @@
5051

5152
from oqpy.program import Program
5253

54+
if sys.version_info < (3, 10):
55+
EllipsisType = type(Ellipsis)
56+
else:
57+
from types import EllipsisType
58+
5359
__all__ = [
5460
"pi",
5561
"ArrayVar",
@@ -242,13 +248,15 @@ class _SizedVar(_ClassicalVar):
242248
default_size: int | None = None
243249
size: int | None
244250

245-
def __class_getitem__(cls: Type[_SizedVarT], item: int) -> Callable[..., _SizedVarT]:
251+
def __class_getitem__(cls: Type[_SizedVarT], item: int | None) -> Callable[..., _SizedVarT]:
246252
# Allows IntVar[64]() notation
247253
return functools.partial(cls, size=item)
248254

249-
def __init__(self, *args: Any, size: int | None = None, **kwargs: Any):
250-
if size is None:
255+
def __init__(self, *args: Any, size: int | None | EllipsisType = ..., **kwargs: Any):
256+
if size is ...:
251257
self.size = self.default_size
258+
elif size is None:
259+
self.size = size
252260
else:
253261
if not isinstance(size, int) or size <= 0:
254262
raise ValueError(

tests/test_directives.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,13 +116,14 @@ def test_version_string():
116116
def test_variable_declaration():
117117
b = BoolVar(True, "b")
118118
i = IntVar(-4, "i")
119+
j = IntVar[None](4, "j")
119120
u = UintVar(5, "u")
120121
x = DurationVar(100e-9, "blah")
121122
y = FloatVar[50](3.3, "y")
122123
ang = AngleVar(name="ang")
123124
arr = BitVar[20](name="arr")
124125
c = BitVar(name="c")
125-
vars = [b, i, u, x, y, ang, arr, c]
126+
vars = [b, i, j, u, x, y, ang, arr, c]
126127

127128
prog = Program(version=None)
128129
prog.declare(vars)
@@ -154,6 +155,7 @@ def test_variable_declaration():
154155
int[32] index = 2;
155156
bool b = true;
156157
int[32] i = -4;
158+
int j = 4;
157159
uint[32] u = 5;
158160
duration blah = 100.0ns;
159161
float[50] y = 3.3;

0 commit comments

Comments
 (0)