# Buggy code
def __init__(
    self,
    num_qubits: Optional[int] = None,
    rotation_blocks: Optional[
        Union[QuantumCircuit, List[QuantumCircuit], Instruction, List[Instruction]]
    ] = None,
    entanglement_blocks: Optional[
        Union[QuantumCircuit, List[QuantumCircuit], Instruction, List[Instruction]]
    ] = None,
    entanglement: Optional[Union[List[int], List[List[int]]]] = None,
    reps: int = 1,
    insert_barriers: bool = False,
    parameter_prefix: str = "θ",
    overwrite_block_parameters: Union[bool, List[List[Parameter]]] = True,
    skip_final_rotation_layer: bool = False,
    skip_unentangled_qubits: bool = False,
    initial_state: Optional[Any] = None,
    name: Optional[str] = "nlocal",
) -> None:
    """Create a new n-local circuit.

    Args:
        num_qubits: The number of qubits of the circuit.
        rotation_blocks: The blocks used in the rotation layers. If multiple are passed,
            these will be applied one after another (like new sub-layers).
        entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed,
            these will be applied one after another. To use different enganglements for
            the sub-layers, see :meth:`get_entangler_map`.
        entanglement: The indices specifying on which qubits the input blocks act. If None, the
            entanglement blocks are applied at the top of the circuit.
        reps: Specifies how often the rotation blocks and entanglement blocks are repeated.
        insert_barriers: If True, barriers are inserted in between each layer. If False,
            no barriers are inserted.
        parameter_prefix: The prefix used if default parameters are generated.
        overwrite_block_parameters: If the parameters in the added blocks should be overwritten.
            If False, the parameters in the blocks are not changed.
        skip_final_rotation_layer: Whether a final rotation layer is added to the circuit.
        skip_unentangled_qubits: If ``True``, the rotation gates act only on qubits that
            are entangled. If ``False``, the rotation gates act on all qubits.
        initial_state: A `qiskit.aqua.components.initial_states.InitialState` object which can
            be used to describe an initial state prepended to the NLocal circuit. This
            is primarily for compatibility with algorithms in Qiskit Aqua, which leverage
            this object to prepare input states.
        name: The name of the circuit.

    Examples:
        TODO

    Raises:
        ImportError: If an ``initial_state`` is specified but Qiskit Aqua is not installed.
        TypeError: If an ``initial_state`` is specified but not of the correct type,
            ``qiskit.aqua.components.initial_states.InitialState``.

    """
    super().__init__(name=name)

    self._num_qubits = None
    self._insert_barriers = insert_barriers
    self._reps = reps
    self._entanglement_blocks = []
    self._rotation_blocks = []
    self._prepended_blocks = []
    self._prepended_entanglement = []
    self._appended_blocks = []
    self._appended_entanglement = []
    self._entanglement = None
    self._entangler_maps = None
    self._ordered_parameters = ParameterVector(name=parameter_prefix)
    self._overwrite_block_parameters = overwrite_block_parameters
    self._skip_final_rotation_layer = skip_final_rotation_layer
    self._skip_unentangled_qubits = skip_unentangled_qubits
    self._initial_state, self._initial_state_circuit = None, None
    self._data = None
    self._bounds = None

    if num_qubits is not None:
        self.num_qubits = num_qubits

    if entanglement_blocks is not None:
        self.entanglement_blocks = entanglement_blocks

    if rotation_blocks is not None:
        self.rotation_blocks = rotation_blocks

    if entanglement is not None:
        self.entanglement = entanglement

    if initial_state is not None:
        try:
            from qiskit.aqua.components.initial_states import InitialState

            if not isinstance(initial_state, InitialState):
                raise TypeError(
                    "initial_state must be of type InitialState, but is {}.".format(
                        type(initial_state)
                    )
                )
        except ImportError:
            raise ImportError(
                "Could not import the qiskit.aqua.components.initial_states."
                "InitialState. To use this feature Qiskit Aqua must be installed."
            )
        self.initial_state = initial_state


# Traceback (UnboundLocalError)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-7-664a076be942> in <module>
----> 1 print(NLocal(1, reps=0))

~/envs/qopt/lib/python3.7/site-packages/qiskit/circuit/library/n_local/n_local.py in __str__(self)
920                        'cswap', 'ccx', 'cu1', 'cu3', 'u1', 'u2', 'u3']
921         return transpile(self, basis_gates=basis_gates,
--> 922                          optimization_level=0).draw(output='text').single_string()
923
924

~/envs/qopt/lib/python3.7/site-packages/qiskit/compiler/transpile.py in transpile(circuits, backend, basis_gates, coupling_map, backend_properties, initial_layout, layout_method, routing_method, translation_method, seed_transpiler, optimization_level, pass_manager, callback, output_name)
214
215     # Transpile circuits in parallel
--> 216     circuits = parallel_map(_transpile_circuit, list(zip(circuits, transpile_args)))
217
218     if len(circuits) == 1:

~/envs/qopt/lib/python3.7/site-packages/qiskit/tools/parallel.py in parallel_map(task, values, task_args, task_kwargs, num_processes)
106         return []
107     if len(values) == 1:
--> 108         return [task(values[0], *task_args, **task_kwargs)]
109
110     Publisher().publish("terra.parallel.start", len(values))

~/envs/qopt/lib/python3.7/site-packages/qiskit/compiler/transpile.py in _transpile_circuit(circuit_config_tuple)
315
316     result = pass_manager.run(circuit, callback=transpile_config['callback'],
--> 317                               output_name=transpile_config['output_name'])
318
319     if transpile_config['faulty_qubits_map']:

~/envs/qopt/lib/python3.7/site-packages/qiskit/transpiler/passmanager.py in run(self, circuits, output_name, callback)
212         """
213         if isinstance(circuits, QuantumCircuit):
--> 214             return self._run_single_circuit(circuits, output_name, callback)
215         elif len(circuits) == 1:
216             return self._run_single_circuit(circuits[0], output_name, callback)

~/envs/qopt/lib/python3.7/site-packages/qiskit/transpiler/passmanager.py in _run_single_circuit(self, circuit, output_name, callback)
275         if callback is None and self.callback:  # TODO to remove with __init__(callback)
276             callback = self.callback
--> 277         result = running_passmanager.run(circuit, output_name=output_name, callback=callback)
278         self.property_set = running_passmanager.property_set
279         return result

~/envs/qopt/lib/python3.7/site-packages/qiskit/transpiler/runningpassmanager.py in run(self, circuit, output_name, callback)
105         """
106         name = circuit.name
--> 107         dag = circuit_to_dag(circuit)
108         del circuit
109

~/envs/qopt/lib/python3.7/site-packages/qiskit/converters/circuit_to_dag.py in circuit_to_dag(circuit)
55         dagcircuit.add_creg(register)
56
---> 57     for instruction, qargs, cargs in circuit.data:
58         dagcircuit.apply_operation_back(instruction.copy(), qargs, cargs)
59     return dagcircuit

~/envs/qopt/lib/python3.7/site-packages/qiskit/circuit/library/blueprintcircuit.py in data(self)
90     def data(self):
91         if self._data is None:
---> 92             self._build()
93         return super().data
94

~/envs/qopt/lib/python3.7/site-packages/qiskit/circuit/library/n_local/n_local.py in _build(self)
899             if self.insert_barriers:
900                 self.barrier()
--> 901             self._build_rotation_layer(param_iter, i)
902
903         # add the appended layers

UnboundLocalError: local variable 'i' referenced before assignment

# Fixed code
def __init__(
    self,
    num_qubits: Optional[int] = None,
    rotation_blocks: Optional[
        Union[QuantumCircuit, List[QuantumCircuit], Instruction, List[Instruction]]
    ] = None,
    entanglement_blocks: Optional[
        Union[QuantumCircuit, List[QuantumCircuit], Instruction, List[Instruction]]
    ] = None,
    entanglement: Optional[Union[List[int], List[List[int]]]] = None,
    reps: int = 1,
    insert_barriers: bool = False,
    parameter_prefix: str = "θ",
    overwrite_block_parameters: Union[bool, List[List[Parameter]]] = True,
    skip_final_rotation_layer: bool = False,
    skip_unentangled_qubits: bool = False,
    initial_state: Optional[Any] = None,
    name: Optional[str] = "nlocal",
) -> None:
    """Create a new n-local circuit.

    Args:
        num_qubits: The number of qubits of the circuit.
        rotation_blocks: The blocks used in the rotation layers. If multiple are passed,
            these will be applied one after another (like new sub-layers).
        entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed,
            these will be applied one after another. To use different enganglements for
            the sub-layers, see :meth:`get_entangler_map`.
        entanglement: The indices specifying on which qubits the input blocks act. If None, the
            entanglement blocks are applied at the top of the circuit.
        reps: Specifies how often the rotation blocks and entanglement blocks are repeated.
        insert_barriers: If True, barriers are inserted in between each layer. If False,
            no barriers are inserted.
        parameter_prefix: The prefix used if default parameters are generated.
        overwrite_block_parameters: If the parameters in the added blocks should be overwritten.
            If False, the parameters in the blocks are not changed.
        skip_final_rotation_layer: Whether a final rotation layer is added to the circuit.
        skip_unentangled_qubits: If ``True``, the rotation gates act only on qubits that
            are entangled. If ``False``, the rotation gates act on all qubits.
        initial_state: A `qiskit.aqua.components.initial_states.InitialState` object which can
            be used to describe an initial state prepended to the NLocal circuit. This
            is primarily for compatibility with algorithms in Qiskit Aqua, which leverage
            this object to prepare input states.
        name: The name of the circuit.

    Examples:
        TODO

    Raises:
        ImportError: If an ``initial_state`` is specified but Qiskit Aqua is not installed.
        TypeError: If an ``initial_state`` is specified but not of the correct type,
            ``qiskit.aqua.components.initial_states.InitialState``.
        ValueError: If reps parameter is less than or equal to 0.
    """
    super().__init__(name=name)

    self._num_qubits = None
    self._insert_barriers = insert_barriers
    self._reps = reps
    self._entanglement_blocks = []
    self._rotation_blocks = []
    self._prepended_blocks = []
    self._prepended_entanglement = []
    self._appended_blocks = []
    self._appended_entanglement = []
    self._entanglement = None
    self._entangler_maps = None
    self._ordered_parameters = ParameterVector(name=parameter_prefix)
    self._overwrite_block_parameters = overwrite_block_parameters
    self._skip_final_rotation_layer = skip_final_rotation_layer
    self._skip_unentangled_qubits = skip_unentangled_qubits
    self._initial_state, self._initial_state_circuit = None, None
    self._data = None
    self._bounds = None

    if reps <= 0:
        raise ValueError("The value of reps should be larger than or equal to 1")

    if num_qubits is not None:
        self.num_qubits = num_qubits

    if entanglement_blocks is not None:
        self.entanglement_blocks = entanglement_blocks

    if rotation_blocks is not None:
        self.rotation_blocks = rotation_blocks

    if entanglement is not None:
        self.entanglement = entanglement

    if initial_state is not None:
        try:
            from qiskit.aqua.components.initial_states import InitialState

            if not isinstance(initial_state, InitialState):
                raise TypeError(
                    "initial_state must be of type InitialState, but is {}.".format(
                        type(initial_state)
                    )
                )
        except ImportError:
            raise ImportError(
                "Could not import the qiskit.aqua.components.initial_states."
                "InitialState. To use this feature Qiskit Aqua must be installed."
            )
        self.initial_state = initial_state