Skip to content

Commit

Permalink
Make LineQubit and GridQubit immutable (#2756)
Browse files Browse the repository at this point in the history
Coordinates of qubits on line or grid now are properties and can't be changed.

Fixes #2356.
  • Loading branch information
fedimser committed Feb 11, 2020
1 parent 68ca843 commit 926751d
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 3 deletions.
12 changes: 10 additions & 2 deletions cirq/devices/grid_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,20 @@ class GridQubit(ops.Qid):
"""

def __init__(self, row: int, col: int):
self.row = row
self.col = col
self._row = row
self._col = col

def _comparison_key(self):
return self.row, self.col

@property
def row(self) -> int:
return self._row

@property
def col(self) -> int:
return self._col

@property
def dimension(self) -> int:
return 2
Expand Down
10 changes: 10 additions & 0 deletions cirq/devices/grid_qubit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,13 @@ def test_to_json():
'row': 5,
'col': 6,
}


def test_immutable():
with pytest.raises(AttributeError, match="can't set attribute"):
q = cirq.GridQubit(1, 2)
q.col = 3

with pytest.raises(AttributeError, match="can't set attribute"):
q = cirq.GridQubit(1, 2)
q.row = 3
6 changes: 5 additions & 1 deletion cirq/devices/line_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,15 @@ class _BaseLineQid(ops.Qid):

def __init__(self, x: int) -> None:
"""Initializes a line qubit at the given x coordinate."""
self.x = x
self._x = x

def _comparison_key(self):
return self.x

@property
def x(self) -> int:
return self._x

def with_dimension(self, dimension: int) -> 'LineQid':
return LineQid(self.x, dimension)

Expand Down
10 changes: 10 additions & 0 deletions cirq/devices/line_qubit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,3 +258,13 @@ def _qid_shape_(self):
cirq.LineQid(3, 3),
cirq.LineQid(2, 1),
]


def test_immutable():
with pytest.raises(AttributeError, match="can't set attribute"):
q = cirq.LineQubit(5)
q.x = 6

with pytest.raises(AttributeError, match="can't set attribute"):
q = cirq.LineQid(5, dimension=4)
q.x = 6

0 comments on commit 926751d

Please sign in to comment.