From a4f2e11a6263749298d647dd4d3c1dd67a1cbacd Mon Sep 17 00:00:00 2001 From: Jim Garrison Date: Mon, 11 Sep 2023 21:34:37 -0400 Subject: [PATCH] Use "raise from" in `except` blocks This is something that pylint should have caught if we were using it (#146). This way, the tracebacks will say > The above exception was the direct cause of the following exception: rather than > During handling of the above exception, another exception occurred: --- circuit_knitting/cutting/cutting_experiments.py | 4 ++-- circuit_knitting/cutting/cutting_reconstruction.py | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/circuit_knitting/cutting/cutting_experiments.py b/circuit_knitting/cutting/cutting_experiments.py index aeeba4f1a..1412b6d5c 100644 --- a/circuit_knitting/cutting/cutting_experiments.py +++ b/circuit_knitting/cutting/cutting_experiments.py @@ -182,7 +182,7 @@ def _get_mapping_ids_by_partition( if isinstance(inst.operation, SingleQubitQPDGate): try: decomp_id = int(inst.operation.label.split("_")[-1]) - except (AttributeError, ValueError): + except (AttributeError, ValueError) as ex: raise ValueError( "SingleQubitQPDGate instances in input circuit(s) must have their " 'labels suffixed with "_", where is the index of the cut ' @@ -190,7 +190,7 @@ def _get_mapping_ids_by_partition( "SingleQubitQPDGates belonging to the same cut, N, should have labels " ' formatted as "_N". This allows SingleQubitQPDGates ' "belonging to the same cut to be sampled jointly." - ) + ) from ex decomp_ids.add(decomp_id) subcirc_qpd_gate_ids[label].append([i]) subcirc_map_ids[label].append(decomp_id) diff --git a/circuit_knitting/cutting/cutting_reconstruction.py b/circuit_knitting/cutting/cutting_reconstruction.py index dbd297267..ec7c68ede 100644 --- a/circuit_knitting/cutting/cutting_reconstruction.py +++ b/circuit_knitting/cutting/cutting_reconstruction.py @@ -115,11 +115,11 @@ def reconstruct_expectation_values( num_qpd_bits = results_dict[label].metadata[ i * len(so.groups) + k ]["num_qpd_bits"] - except KeyError: + except KeyError as ex: raise ValueError( "The num_qpd_bits field must be set in each subexperiment " "result metadata dictionary." - ) + ) from ex else: subsystem_expvals[k] += quasi_prob * _process_outcome( num_qpd_bits, @@ -159,10 +159,10 @@ def _process_outcome( outcome = _outcome_to_int(outcome) try: qpd_outcomes = outcome & ((1 << num_qpd_bits) - 1) - except TypeError: + except TypeError as ex: raise TypeError( f"num_qpd_bits must be an integer, but a {type(num_qpd_bits)} was passed." - ) + ) from ex meas_outcomes = outcome >> num_qpd_bits