We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Document naming of CircuitInstruction and related classes
### What should we add?

I asked @jakelishman why CircuitInstruction is named that way when it is not an Instruction, and why it has an attribute named `operation` which is actually an Instruction. He replied:
>it’s because what’s currently called Instruction shouldn’t really be called that, but we can’t change it without breaking everything.  So instead, the new interface definition for “something that can be added to QuantumCircuit is called Operation, and the container is CircuitInstruction to avoid the naming clash

This should be publicly documented somewhere to mitigate user confusion.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `qiskit/circuit/quantumcircuitdata.py`
Content:
```
1 # This code is part of Qiskit.
2 #
3 # (C) Copyright IBM 2019.
4 #
5 # This code is licensed under the Apache License, Version 2.0. You may
6 # obtain a copy of this license in the LICENSE.txt file in the root directory
7 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8 #
9 # Any modifications or derivative works of this code must retain this
10 # copyright notice, and modified files need to carry a notice indicating
11 # that they have been altered from the originals.
12 
13 """A wrapper class for the purposes of validating modifications to
14 QuantumCircuit.data while maintaining the interface of a python list."""
15 
16 from collections.abc import MutableSequence
17 from typing import Tuple, Iterable, Optional
18 
19 from .exceptions import CircuitError
20 from .instruction import Instruction
21 from .quantumregister import Qubit
22 from .classicalregister import Clbit
23 
24 
25 class CircuitInstruction:
26     """A single instruction in a :class:`.QuantumCircuit`, comprised of the :attr:`operation` and
27     various operands.
28 
29     .. warning::
30 
31         This is a lightweight internal class and there is minimal error checking; you must respect
32         the type hints when using it.  It is the user's responsibility to ensure that direct
33         mutations of the object do not invalidate the types, nor the restrictions placed on it by
34         its context.  Typically this will mean, for example, that :attr:`qubits` must be a sequence
35         of distinct items, with no duplicates.
36     """
37 
38     __slots__ = ("operation", "qubits", "clbits", "_legacy_format_cache")
39 
40     operation: Instruction
41     """The logical operation that this instruction represents an execution of."""
42     qubits: Tuple[Qubit, ...]
43     """A sequence of the qubits that the operation is applied to."""
44     clbits: Tuple[Clbit, ...]
45     """A sequence of the classical bits that this operation reads from or writes to."""
46 
47     def __init__(
48         self,
49         operation: Instruction,
50         qubits: Iterable[Qubit] = (),
51         clbits: Iterable[Clbit] = (),
52     ):
53         self.operation = operation
54         self.qubits = tuple(qubits)
55         self.clbits = tuple(clbits)
56         self._legacy_format_cache = None
57 
58     def copy(self) -> "CircuitInstruction":
59         """Return a shallow copy of the :class:`CircuitInstruction`."""
60         return self.__class__(
61             operation=self.operation,
62             qubits=self.qubits,
63             clbits=self.clbits,
64         )
65 
66     def replace(
67         self,
68         operation: Optional[Instruction] = None,
69         qubits: Optional[Iterable[Qubit]] = None,
70         clbits: Optional[Iterable[Clbit]] = None,
71     ) -> "CircuitInstruction":
72         """Return a new :class:`CircuitInstruction` with the given fields replaced."""
73         return self.__class__(
74             operation=self.operation if operation is None else operation,
75             qubits=self.qubits if qubits is None else qubits,
76             clbits=self.clbits if clbits is None else clbits,
77         )
78 
79     def __repr__(self):
80         return (
81             f"{type(self).__name__}("
82             f"operation={self.operation!r}"
83             f", qubits={self.qubits!r}"
84             f", clbits={self.clbits!r}"
85             ")"
86         )
87 
88     def __eq__(self, other):
89         if isinstance(other, type(self)):
90             # Ordered from fastest comparisons to slowest.
91             return (
92                 self.clbits == other.clbits
93                 and self.qubits == other.qubits
94                 and self.operation == other.operation
95             )
96         if isinstance(other, tuple):
97             return self._legacy_format == other
98         return NotImplemented
99 
100     # Legacy tuple-like interface support.
101     #
102     # For a best attempt at API compatibility during the transition to using this new class, we need
103     # the interface to behave exactly like the old 3-tuple `(inst, qargs, cargs)` if it's treated
104     # like that via unpacking or similar.  That means that the `parameters` field is completely
105     # absent, and the qubits and clbits must be converted to lists.
106 
107     @property
108     def _legacy_format(self):
109         if self._legacy_format_cache is None:
110             # The qubits and clbits were generally stored as lists in the old format, and various
111             # places assume that they will certainly be lists.
112             self._legacy_format_cache = (self.operation, list(self.qubits), list(self.clbits))
113         return self._legacy_format_cache
114 
115     def __getitem__(self, key):
116         return self._legacy_format[key]
117 
118     def __iter__(self):
119         return iter(self._legacy_format)
120 
121     def __len__(self):
122         return 3
123 
124 
125 class QuantumCircuitData(MutableSequence):
126     """A wrapper class for the purposes of validating modifications to
127     QuantumCircuit.data while maintaining the interface of a python list."""
128 
129     def __init__(self, circuit):
130         self._circuit = circuit
131 
132     def __getitem__(self, i):
133         return self._circuit._data[i]
134 
135     def __setitem__(self, key, value):
136         # For now (Terra 0.21), the `QuantumCircuit.data` setter is meant to perform validation, so
137         # we do the same qubit checks that `QuantumCircuit.append` would do.
138         if isinstance(value, CircuitInstruction):
139             operation, qargs, cargs = value.operation, value.qubits, value.clbits
140         else:
141             # Handle the legacy 3-tuple format.
142             operation, qargs, cargs = value
143         value = self._resolve_legacy_value(operation, qargs, cargs)
144         self._circuit._data[key] = value
145         self._circuit._update_parameter_table(value)
146 
147     def _resolve_legacy_value(self, operation, qargs, cargs) -> CircuitInstruction:
148         """Resolve the old-style 3-tuple into the new :class:`CircuitInstruction` type."""
149         if not isinstance(operation, Instruction) and hasattr(operation, "to_instruction"):
150             operation = operation.to_instruction()
151         if not isinstance(operation, Instruction):
152             raise CircuitError("object is not an Instruction.")
153 
154         expanded_qargs = [self._circuit.qbit_argument_conversion(qarg) for qarg in qargs or []]
155         expanded_cargs = [self._circuit.cbit_argument_conversion(carg) for carg in cargs or []]
156 
157         if isinstance(operation, Instruction):
158             broadcast_args = list(operation.broadcast_arguments(expanded_qargs, expanded_cargs))
159         else:
160             broadcast_args = list(
161                 Instruction.broadcast_arguments(operation, expanded_qargs, expanded_cargs)
162             )
163 
164         if len(broadcast_args) > 1:
165             raise CircuitError(
166                 "QuantumCircuit.data modification does not support argument broadcasting."
167             )
168 
169         qargs, cargs = broadcast_args[0]
170 
171         self._circuit._check_dups(qargs)
172         return CircuitInstruction(operation, tuple(qargs), tuple(cargs))
173 
174     def insert(self, index, value):
175         self._circuit._data.insert(index, None)
176         try:
177             self[index] = value
178         except CircuitError:
179             del self._circuit._data[index]
180             raise
181 
182     def __iter__(self):
183         return iter(self._circuit._data)
184 
185     def __delitem__(self, i):
186         del self._circuit._data[i]
187 
188     def __len__(self):
189         return len(self._circuit._data)
190 
191     def __cast(self, other):
192         return other._circuit._data if isinstance(other, QuantumCircuitData) else other
193 
194     def __repr__(self):
195         return repr(self._circuit._data)
196 
197     def __lt__(self, other):
198         return self._circuit._data < self.__cast(other)
199 
200     def __le__(self, other):
201         return self._circuit._data <= self.__cast(other)
202 
203     def __eq__(self, other):
204         return self._circuit._data == self.__cast(other)
205 
206     def __gt__(self, other):
207         return self._circuit._data > self.__cast(other)
208 
209     def __ge__(self, other):
210         return self._circuit._data >= self.__cast(other)
211 
212     def __add__(self, other):
213         return self._circuit._data + self.__cast(other)
214 
215     def __radd__(self, other):
216         return self.__cast(other) + self._circuit._data
217 
218     def __mul__(self, n):
219         return self._circuit._data * n
220 
221     def __rmul__(self, n):
222         return n * self._circuit._data
223 
224     def sort(self, *args, **kwargs):
225         """In-place stable sort. Accepts arguments of list.sort."""
226         self._circuit._data.sort(*args, **kwargs)
227 
228     def copy(self):
229         """Returns a shallow copy of instruction list."""
230         return self._circuit._data.copy()
231
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/qiskit/circuit/quantumcircuitdata.py b/qiskit/circuit/quantumcircuitdata.py
--- a/qiskit/circuit/quantumcircuitdata.py
+++ b/qiskit/circuit/quantumcircuitdata.py
@@ -26,6 +26,28 @@
     """A single instruction in a :class:`.QuantumCircuit`, comprised of the :attr:`operation` and
     various operands.
 
+    .. note::
+
+        There is some possible confusion in the names of this class, :class:`~.circuit.Instruction`,
+        and :class:`~.circuit.Operation`, and this class's attribute :attr:`operation`.  Our
+        preferred terminology is by analogy to assembly languages, where an "instruction" is made up
+        of an "operation" and its "operands".
+
+        Historically, :class:`~.circuit.Instruction` came first, and originally contained the qubits
+        it operated on and any parameters, so it was a true "instruction".  Over time,
+        :class:`.QuantumCircuit` became responsible for tracking qubits and clbits, and the class
+        became better described as an "operation".  Changing the name of such a core object would be
+        a very unpleasant API break for users, and so we have stuck with it.
+
+        This class was created to provide a formal "instruction" context object in
+        :class:`.QuantumCircuit.data`, which had long been made of ad-hoc tuples.  With this, and
+        the advent of the :class:`~.circuit.Operation` interface for adding more complex objects to
+        circuits, we took the opportunity to correct the historical naming.  For the time being,
+        this leads to an awkward case where :attr:`.CircuitInstruction.operation` is often an
+        :class:`~.circuit.Instruction` instance (:class:`~.circuit.Instruction` implements the
+        :class:`.Operation` interface), but as the :class:`.Operation` interface gains more use,
+        this confusion will hopefully abate.
+
     .. warning::
 
         This is a lightweight internal class and there is minimal error checking; you must respect

{"golden_diff": "diff --git a/qiskit/circuit/quantumcircuitdata.py b/qiskit/circuit/quantumcircuitdata.py\n--- a/qiskit/circuit/quantumcircuitdata.py\n+++ b/qiskit/circuit/quantumcircuitdata.py\n@@ -26,6 +26,28 @@\n     \"\"\"A single instruction in a :class:`.QuantumCircuit`, comprised of the :attr:`operation` and\n     various operands.\n \n+    .. note::\n+\n+        There is some possible confusion in the names of this class, :class:`~.circuit.Instruction`,\n+        and :class:`~.circuit.Operation`, and this class's attribute :attr:`operation`.  Our\n+        preferred terminology is by analogy to assembly languages, where an \"instruction\" is made up\n+        of an \"operation\" and its \"operands\".\n+\n+        Historically, :class:`~.circuit.Instruction` came first, and originally contained the qubits\n+        it operated on and any parameters, so it was a true \"instruction\".  Over time,\n+        :class:`.QuantumCircuit` became responsible for tracking qubits and clbits, and the class\n+        became better described as an \"operation\".  Changing the name of such a core object would be\n+        a very unpleasant API break for users, and so we have stuck with it.\n+\n+        This class was created to provide a formal \"instruction\" context object in\n+        :class:`.QuantumCircuit.data`, which had long been made of ad-hoc tuples.  With this, and\n+        the advent of the :class:`~.circuit.Operation` interface for adding more complex objects to\n+        circuits, we took the opportunity to correct the historical naming.  For the time being,\n+        this leads to an awkward case where :attr:`.CircuitInstruction.operation` is often an\n+        :class:`~.circuit.Instruction` instance (:class:`~.circuit.Instruction` implements the\n+        :class:`.Operation` interface), but as the :class:`.Operation` interface gains more use,\n+        this confusion will hopefully abate.\n+\n     .. warning::\n \n         This is a lightweight internal class and there is minimal error checking; you must respect\n", "issue": "Document naming of CircuitInstruction and related classes\n### What should we add?\n\nI asked @jakelishman why CircuitInstruction is named that way when it is not an Instruction, and why it has an attribute named `operation` which is actually an Instruction. He replied:\r\n>it\u2019s because what\u2019s currently called Instruction shouldn\u2019t really be called that, but we can\u2019t change it without breaking everything.  So instead, the new interface definition for \u201csomething that can be added to QuantumCircuit is called Operation, and the container is CircuitInstruction to avoid the naming clash\r\n\r\nThis should be publicly documented somewhere to mitigate user confusion.\n", "before_files": [{"content": "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2019.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"A wrapper class for the purposes of validating modifications to\nQuantumCircuit.data while maintaining the interface of a python list.\"\"\"\n\nfrom collections.abc import MutableSequence\nfrom typing import Tuple, Iterable, Optional\n\nfrom .exceptions import CircuitError\nfrom .instruction import Instruction\nfrom .quantumregister import Qubit\nfrom .classicalregister import Clbit\n\n\nclass CircuitInstruction:\n    \"\"\"A single instruction in a :class:`.QuantumCircuit`, comprised of the :attr:`operation` and\n    various operands.\n\n    .. warning::\n\n        This is a lightweight internal class and there is minimal error checking; you must respect\n        the type hints when using it.  It is the user's responsibility to ensure that direct\n        mutations of the object do not invalidate the types, nor the restrictions placed on it by\n        its context.  Typically this will mean, for example, that :attr:`qubits` must be a sequence\n        of distinct items, with no duplicates.\n    \"\"\"\n\n    __slots__ = (\"operation\", \"qubits\", \"clbits\", \"_legacy_format_cache\")\n\n    operation: Instruction\n    \"\"\"The logical operation that this instruction represents an execution of.\"\"\"\n    qubits: Tuple[Qubit, ...]\n    \"\"\"A sequence of the qubits that the operation is applied to.\"\"\"\n    clbits: Tuple[Clbit, ...]\n    \"\"\"A sequence of the classical bits that this operation reads from or writes to.\"\"\"\n\n    def __init__(\n        self,\n        operation: Instruction,\n        qubits: Iterable[Qubit] = (),\n        clbits: Iterable[Clbit] = (),\n    ):\n        self.operation = operation\n        self.qubits = tuple(qubits)\n        self.clbits = tuple(clbits)\n        self._legacy_format_cache = None\n\n    def copy(self) -> \"CircuitInstruction\":\n        \"\"\"Return a shallow copy of the :class:`CircuitInstruction`.\"\"\"\n        return self.__class__(\n            operation=self.operation,\n            qubits=self.qubits,\n            clbits=self.clbits,\n        )\n\n    def replace(\n        self,\n        operation: Optional[Instruction] = None,\n        qubits: Optional[Iterable[Qubit]] = None,\n        clbits: Optional[Iterable[Clbit]] = None,\n    ) -> \"CircuitInstruction\":\n        \"\"\"Return a new :class:`CircuitInstruction` with the given fields replaced.\"\"\"\n        return self.__class__(\n            operation=self.operation if operation is None else operation,\n            qubits=self.qubits if qubits is None else qubits,\n            clbits=self.clbits if clbits is None else clbits,\n        )\n\n    def __repr__(self):\n        return (\n            f\"{type(self).__name__}(\"\n            f\"operation={self.operation!r}\"\n            f\", qubits={self.qubits!r}\"\n            f\", clbits={self.clbits!r}\"\n            \")\"\n        )\n\n    def __eq__(self, other):\n        if isinstance(other, type(self)):\n            # Ordered from fastest comparisons to slowest.\n            return (\n                self.clbits == other.clbits\n                and self.qubits == other.qubits\n                and self.operation == other.operation\n            )\n        if isinstance(other, tuple):\n            return self._legacy_format == other\n        return NotImplemented\n\n    # Legacy tuple-like interface support.\n    #\n    # For a best attempt at API compatibility during the transition to using this new class, we need\n    # the interface to behave exactly like the old 3-tuple `(inst, qargs, cargs)` if it's treated\n    # like that via unpacking or similar.  That means that the `parameters` field is completely\n    # absent, and the qubits and clbits must be converted to lists.\n\n    @property\n    def _legacy_format(self):\n        if self._legacy_format_cache is None:\n            # The qubits and clbits were generally stored as lists in the old format, and various\n            # places assume that they will certainly be lists.\n            self._legacy_format_cache = (self.operation, list(self.qubits), list(self.clbits))\n        return self._legacy_format_cache\n\n    def __getitem__(self, key):\n        return self._legacy_format[key]\n\n    def __iter__(self):\n        return iter(self._legacy_format)\n\n    def __len__(self):\n        return 3\n\n\nclass QuantumCircuitData(MutableSequence):\n    \"\"\"A wrapper class for the purposes of validating modifications to\n    QuantumCircuit.data while maintaining the interface of a python list.\"\"\"\n\n    def __init__(self, circuit):\n        self._circuit = circuit\n\n    def __getitem__(self, i):\n        return self._circuit._data[i]\n\n    def __setitem__(self, key, value):\n        # For now (Terra 0.21), the `QuantumCircuit.data` setter is meant to perform validation, so\n        # we do the same qubit checks that `QuantumCircuit.append` would do.\n        if isinstance(value, CircuitInstruction):\n            operation, qargs, cargs = value.operation, value.qubits, value.clbits\n        else:\n            # Handle the legacy 3-tuple format.\n            operation, qargs, cargs = value\n        value = self._resolve_legacy_value(operation, qargs, cargs)\n        self._circuit._data[key] = value\n        self._circuit._update_parameter_table(value)\n\n    def _resolve_legacy_value(self, operation, qargs, cargs) -> CircuitInstruction:\n        \"\"\"Resolve the old-style 3-tuple into the new :class:`CircuitInstruction` type.\"\"\"\n        if not isinstance(operation, Instruction) and hasattr(operation, \"to_instruction\"):\n            operation = operation.to_instruction()\n        if not isinstance(operation, Instruction):\n            raise CircuitError(\"object is not an Instruction.\")\n\n        expanded_qargs = [self._circuit.qbit_argument_conversion(qarg) for qarg in qargs or []]\n        expanded_cargs = [self._circuit.cbit_argument_conversion(carg) for carg in cargs or []]\n\n        if isinstance(operation, Instruction):\n            broadcast_args = list(operation.broadcast_arguments(expanded_qargs, expanded_cargs))\n        else:\n            broadcast_args = list(\n                Instruction.broadcast_arguments(operation, expanded_qargs, expanded_cargs)\n            )\n\n        if len(broadcast_args) > 1:\n            raise CircuitError(\n                \"QuantumCircuit.data modification does not support argument broadcasting.\"\n            )\n\n        qargs, cargs = broadcast_args[0]\n\n        self._circuit._check_dups(qargs)\n        return CircuitInstruction(operation, tuple(qargs), tuple(cargs))\n\n    def insert(self, index, value):\n        self._circuit._data.insert(index, None)\n        try:\n            self[index] = value\n        except CircuitError:\n            del self._circuit._data[index]\n            raise\n\n    def __iter__(self):\n        return iter(self._circuit._data)\n\n    def __delitem__(self, i):\n        del self._circuit._data[i]\n\n    def __len__(self):\n        return len(self._circuit._data)\n\n    def __cast(self, other):\n        return other._circuit._data if isinstance(other, QuantumCircuitData) else other\n\n    def __repr__(self):\n        return repr(self._circuit._data)\n\n    def __lt__(self, other):\n        return self._circuit._data < self.__cast(other)\n\n    def __le__(self, other):\n        return self._circuit._data <= self.__cast(other)\n\n    def __eq__(self, other):\n        return self._circuit._data == self.__cast(other)\n\n    def __gt__(self, other):\n        return self._circuit._data > self.__cast(other)\n\n    def __ge__(self, other):\n        return self._circuit._data >= self.__cast(other)\n\n    def __add__(self, other):\n        return self._circuit._data + self.__cast(other)\n\n    def __radd__(self, other):\n        return self.__cast(other) + self._circuit._data\n\n    def __mul__(self, n):\n        return self._circuit._data * n\n\n    def __rmul__(self, n):\n        return n * self._circuit._data\n\n    def sort(self, *args, **kwargs):\n        \"\"\"In-place stable sort. Accepts arguments of list.sort.\"\"\"\n        self._circuit._data.sort(*args, **kwargs)\n\n    def copy(self):\n        \"\"\"Returns a shallow copy of instruction list.\"\"\"\n        return self._circuit._data.copy()\n", "path": "qiskit/circuit/quantumcircuitdata.py"}], "after_files": [{"content": "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2019.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"A wrapper class for the purposes of validating modifications to\nQuantumCircuit.data while maintaining the interface of a python list.\"\"\"\n\nfrom collections.abc import MutableSequence\nfrom typing import Tuple, Iterable, Optional\n\nfrom .exceptions import CircuitError\nfrom .instruction import Instruction\nfrom .quantumregister import Qubit\nfrom .classicalregister import Clbit\n\n\nclass CircuitInstruction:\n    \"\"\"A single instruction in a :class:`.QuantumCircuit`, comprised of the :attr:`operation` and\n    various operands.\n\n    .. note::\n\n        There is some possible confusion in the names of this class, :class:`~.circuit.Instruction`,\n        and :class:`~.circuit.Operation`, and this class's attribute :attr:`operation`.  Our\n        preferred terminology is by analogy to assembly languages, where an \"instruction\" is made up\n        of an \"operation\" and its \"operands\".\n\n        Historically, :class:`~.circuit.Instruction` came first, and originally contained the qubits\n        it operated on and any parameters, so it was a true \"instruction\".  Over time,\n        :class:`.QuantumCircuit` became responsible for tracking qubits and clbits, and the class\n        became better described as an \"operation\".  Changing the name of such a core object would be\n        a very unpleasant API break for users, and so we have stuck with it.\n\n        This class was created to provide a formal \"instruction\" context object in\n        :class:`.QuantumCircuit.data`, which had long been made of ad-hoc tuples.  With this, and\n        the advent of the :class:`~.circuit.Operation` interface for adding more complex objects to\n        circuits, we took the opportunity to correct the historical naming.  For the time being,\n        this leads to an awkward case where :attr:`.CircuitInstruction.operation` is often an\n        :class:`~.circuit.Instruction` instance (:class:`~.circuit.Instruction` implements the\n        :class:`.Operation` interface), but as the :class:`.Operation` interface gains more use,\n        this confusion will hopefully abate.\n\n    .. warning::\n\n        This is a lightweight internal class and there is minimal error checking; you must respect\n        the type hints when using it.  It is the user's responsibility to ensure that direct\n        mutations of the object do not invalidate the types, nor the restrictions placed on it by\n        its context.  Typically this will mean, for example, that :attr:`qubits` must be a sequence\n        of distinct items, with no duplicates.\n    \"\"\"\n\n    __slots__ = (\"operation\", \"qubits\", \"clbits\", \"_legacy_format_cache\")\n\n    operation: Instruction\n    \"\"\"The logical operation that this instruction represents an execution of.\"\"\"\n    qubits: Tuple[Qubit, ...]\n    \"\"\"A sequence of the qubits that the operation is applied to.\"\"\"\n    clbits: Tuple[Clbit, ...]\n    \"\"\"A sequence of the classical bits that this operation reads from or writes to.\"\"\"\n\n    def __init__(\n        self,\n        operation: Instruction,\n        qubits: Iterable[Qubit] = (),\n        clbits: Iterable[Clbit] = (),\n    ):\n        self.operation = operation\n        self.qubits = tuple(qubits)\n        self.clbits = tuple(clbits)\n        self._legacy_format_cache = None\n\n    def copy(self) -> \"CircuitInstruction\":\n        \"\"\"Return a shallow copy of the :class:`CircuitInstruction`.\"\"\"\n        return self.__class__(\n            operation=self.operation,\n            qubits=self.qubits,\n            clbits=self.clbits,\n        )\n\n    def replace(\n        self,\n        operation: Optional[Instruction] = None,\n        qubits: Optional[Iterable[Qubit]] = None,\n        clbits: Optional[Iterable[Clbit]] = None,\n    ) -> \"CircuitInstruction\":\n        \"\"\"Return a new :class:`CircuitInstruction` with the given fields replaced.\"\"\"\n        return self.__class__(\n            operation=self.operation if operation is None else operation,\n            qubits=self.qubits if qubits is None else qubits,\n            clbits=self.clbits if clbits is None else clbits,\n        )\n\n    def __repr__(self):\n        return (\n            f\"{type(self).__name__}(\"\n            f\"operation={self.operation!r}\"\n            f\", qubits={self.qubits!r}\"\n            f\", clbits={self.clbits!r}\"\n            \")\"\n        )\n\n    def __eq__(self, other):\n        if isinstance(other, type(self)):\n            # Ordered from fastest comparisons to slowest.\n            return (\n                self.clbits == other.clbits\n                and self.qubits == other.qubits\n                and self.operation == other.operation\n            )\n        if isinstance(other, tuple):\n            return self._legacy_format == other\n        return NotImplemented\n\n    # Legacy tuple-like interface support.\n    #\n    # For a best attempt at API compatibility during the transition to using this new class, we need\n    # the interface to behave exactly like the old 3-tuple `(inst, qargs, cargs)` if it's treated\n    # like that via unpacking or similar.  That means that the `parameters` field is completely\n    # absent, and the qubits and clbits must be converted to lists.\n\n    @property\n    def _legacy_format(self):\n        if self._legacy_format_cache is None:\n            # The qubits and clbits were generally stored as lists in the old format, and various\n            # places assume that they will certainly be lists.\n            self._legacy_format_cache = (self.operation, list(self.qubits), list(self.clbits))\n        return self._legacy_format_cache\n\n    def __getitem__(self, key):\n        return self._legacy_format[key]\n\n    def __iter__(self):\n        return iter(self._legacy_format)\n\n    def __len__(self):\n        return 3\n\n\nclass QuantumCircuitData(MutableSequence):\n    \"\"\"A wrapper class for the purposes of validating modifications to\n    QuantumCircuit.data while maintaining the interface of a python list.\"\"\"\n\n    def __init__(self, circuit):\n        self._circuit = circuit\n\n    def __getitem__(self, i):\n        return self._circuit._data[i]\n\n    def __setitem__(self, key, value):\n        # For now (Terra 0.21), the `QuantumCircuit.data` setter is meant to perform validation, so\n        # we do the same qubit checks that `QuantumCircuit.append` would do.\n        if isinstance(value, CircuitInstruction):\n            operation, qargs, cargs = value.operation, value.qubits, value.clbits\n        else:\n            # Handle the legacy 3-tuple format.\n            operation, qargs, cargs = value\n        value = self._resolve_legacy_value(operation, qargs, cargs)\n        self._circuit._data[key] = value\n        self._circuit._update_parameter_table(value)\n\n    def _resolve_legacy_value(self, operation, qargs, cargs) -> CircuitInstruction:\n        \"\"\"Resolve the old-style 3-tuple into the new :class:`CircuitInstruction` type.\"\"\"\n        if not isinstance(operation, Instruction) and hasattr(operation, \"to_instruction\"):\n            operation = operation.to_instruction()\n        if not isinstance(operation, Instruction):\n            raise CircuitError(\"object is not an Instruction.\")\n\n        expanded_qargs = [self._circuit.qbit_argument_conversion(qarg) for qarg in qargs or []]\n        expanded_cargs = [self._circuit.cbit_argument_conversion(carg) for carg in cargs or []]\n\n        if isinstance(operation, Instruction):\n            broadcast_args = list(operation.broadcast_arguments(expanded_qargs, expanded_cargs))\n        else:\n            broadcast_args = list(\n                Instruction.broadcast_arguments(operation, expanded_qargs, expanded_cargs)\n            )\n\n        if len(broadcast_args) > 1:\n            raise CircuitError(\n                \"QuantumCircuit.data modification does not support argument broadcasting.\"\n            )\n\n        qargs, cargs = broadcast_args[0]\n\n        self._circuit._check_dups(qargs)\n        return CircuitInstruction(operation, tuple(qargs), tuple(cargs))\n\n    def insert(self, index, value):\n        self._circuit._data.insert(index, None)\n        try:\n            self[index] = value\n        except CircuitError:\n            del self._circuit._data[index]\n            raise\n\n    def __iter__(self):\n        return iter(self._circuit._data)\n\n    def __delitem__(self, i):\n        del self._circuit._data[i]\n\n    def __len__(self):\n        return len(self._circuit._data)\n\n    def __cast(self, other):\n        return other._circuit._data if isinstance(other, QuantumCircuitData) else other\n\n    def __repr__(self):\n        return repr(self._circuit._data)\n\n    def __lt__(self, other):\n        return self._circuit._data < self.__cast(other)\n\n    def __le__(self, other):\n        return self._circuit._data <= self.__cast(other)\n\n    def __eq__(self, other):\n        return self._circuit._data == self.__cast(other)\n\n    def __gt__(self, other):\n        return self._circuit._data > self.__cast(other)\n\n    def __ge__(self, other):\n        return self._circuit._data >= self.__cast(other)\n\n    def __add__(self, other):\n        return self._circuit._data + self.__cast(other)\n\n    def __radd__(self, other):\n        return self.__cast(other) + self._circuit._data\n\n    def __mul__(self, n):\n        return self._circuit._data * n\n\n    def __rmul__(self, n):\n        return n * self._circuit._data\n\n    def sort(self, *args, **kwargs):\n        \"\"\"In-place stable sort. Accepts arguments of list.sort.\"\"\"\n        self._circuit._data.sort(*args, **kwargs)\n\n    def copy(self):\n        \"\"\"Returns a shallow copy of instruction list.\"\"\"\n        return self._circuit._data.copy()\n", "path": "qiskit/circuit/quantumcircuitdata.py"}]}