Skip to content

Commit

Permalink
Format automatically covered lines with flynt (#3786)
Browse files Browse the repository at this point in the history
[Flynt: A tool to automatically convert old string literal formatting to f-strings](https://github.com/ikamensh/flynt)

What I did was

```
$ pip install flynt
$ flynt .
```
This is the first half to #3804
  • Loading branch information
vtomole committed Mar 10, 2021
1 parent 2b948ba commit 7a335e3
Show file tree
Hide file tree
Showing 133 changed files with 445 additions and 465 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ jobs:
with:
python-version: '3.7'
architecture: 'x64'
- name: Install flynt
run: cat dev_tools/conf/pip-list-dev-tools.txt | grep flynt | xargs pip install
- name: Install black
run: cat dev_tools/conf/pip-list-dev-tools.txt | grep black | xargs pip install
- name: Format
Expand Down
18 changes: 14 additions & 4 deletions check/format-incremental
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
# Usage:
# check/format-incremental [BASE_REVISION] [--apply] [--all]
#
# By default, the script analyzes python files that have changed relative to the
# By default, the script runs flynt to convert old string literal formatting to f-strings
# and analyzes python files that have changed relative to the
# base revision and determines whether they need to be formatted. If any changes
# are needed, it prints the diff and exits with code 1, otherwise it exits with
# code 0.
Expand Down Expand Up @@ -34,6 +35,11 @@
cd "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$(git rev-parse --show-toplevel)"

# TODO: Remove '-e cirq/ops/pauli_string.py' once the line is covered (https://github.com/quantumlib/Cirq/issues/3804)
flynt cirq dev_tools examples -f -e cirq/ops/pauli_string.py

FLYNTSTATUS=$?

# Parse arguments.
only_print=1
only_changed=1
Expand Down Expand Up @@ -114,9 +120,13 @@ fi
# black "${args[@]}" ${format_files}
# exit $?
LOGS="$(black "${args[@]}" ${format_files} 2>&1)"
STATUS=$?
BLACKSTATUS=$?
echo "${LOGS}"
if [[ "$STATUS" == "123" && "$LOGS" =~ ^.*"INTERNAL ERROR: Black produced different code on the second pass of the formatter.".*$ ]]; then
if [[ "$BLACKSTATUS" == "123" && "$LOGS" =~ ^.*"INTERNAL ERROR: Black produced different code on the second pass of the formatter.".*$ ]]; then
echo -e "\033[31mWarning, it seems we ran into https://github.com/psf/black/issues/1629. Typically, this can be fixed by adding a trailing comma. If you get stuck, please file a cirq issue on github.\033[0m"
fi
exit $STATUS

if [[ "$FLYNTSTATUS" != "0" || "$BLACKSTATUS" != "0" ]]; then
exit 1
fi
exit 0
4 changes: 2 additions & 2 deletions cirq/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ def proper_repr(value: Any) -> str:

if isinstance(value, np.ndarray):
if np.issubdtype(value.dtype, np.datetime64):
return 'np.array({!r}, dtype=np.{!r})'.format(value.tolist(), value.dtype)
return 'np.array({!r}, dtype=np.{})'.format(value.tolist(), value.dtype)
return f'np.array({value.tolist()!r}, dtype=np.{value.dtype!r})'
return f'np.array({value.tolist()!r}, dtype=np.{value.dtype})'

if isinstance(value, pd.MultiIndex):
return f'pd.MultiIndex.from_tuples({repr(list(value))}, names={repr(list(value.names))})'
Expand Down
2 changes: 1 addition & 1 deletion cirq/aqt/aqt_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def _send_json(
measurements_int = data['samples']
measurements = np.zeros((len(measurements_int), num_qubits))
for i, result_int in enumerate(measurements_int):
measurement_int_bin = format(result_int, '0{}b'.format(num_qubits))
measurement_int_bin = format(result_int, f'0{num_qubits}b')
for j in range(num_qubits):
measurements[i, j] = int(measurement_int_bin[j])
return measurements
Expand Down
2 changes: 1 addition & 1 deletion cirq/circuits/_box_drawing_character_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def parts_with(val: int) -> List[str]:
return getattr(self.second_char_set, second_key)
if not second_key:
return getattr(self.first_char_set, first_key)
return getattr(self, '{}_then_{}'.format(first_key, second_key))
return getattr(self, f'{first_key}_then_{second_key}')


NORMAL_BOX_CHARS = BoxDrawCharacterSet(
Expand Down
2 changes: 1 addition & 1 deletion cirq/circuits/_bucket_priority_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def dequeue(self) -> Tuple[int, TItem]:
return priority, item

def __str__(self) -> str:
lines = ['{}: {},'.format(p, e) for p, e in self]
lines = [f'{p}: {e},' for p, e in self]
return 'BucketPriorityQueue {' + _indent(lines) + '\n}'

def __repr__(self) -> str:
Expand Down
18 changes: 9 additions & 9 deletions cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ def next_moment_operating_on(
if max_distance is None:
max_distance = max_circuit_distance
elif max_distance < 0:
raise ValueError('Negative max_distance: {}'.format(max_distance))
raise ValueError(f'Negative max_distance: {max_distance}')
else:
max_distance = min(max_distance, max_circuit_distance)

Expand Down Expand Up @@ -341,7 +341,7 @@ def prev_moment_operating_on(
if max_distance is None:
max_distance = len(self.moments)
elif max_distance < 0:
raise ValueError('Negative max_distance: {}'.format(max_distance))
raise ValueError(f'Negative max_distance: {max_distance}')
else:
max_distance = min(end_moment_index, max_distance)

Expand Down Expand Up @@ -1191,7 +1191,7 @@ def _to_qasm_output(
register.
"""
if header is None:
header = 'Generated from Cirq v{}'.format(cirq._version.__version__)
header = f'Generated from Cirq v{cirq._version.__version__}'
qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(self.all_qubits())
return QasmOutput(
operations=self.all_operations(),
Expand Down Expand Up @@ -1783,7 +1783,7 @@ def _pick_or_create_inserted_op_moment_index(
splitter_index, op, InsertStrategy.INLINE
)

raise ValueError('Unrecognized append strategy: {}'.format(strategy))
raise ValueError(f'Unrecognized append strategy: {strategy}')

def _can_add_op_at(self, moment_index: int, operation: 'cirq.Operation') -> bool:
if not 0 <= moment_index < len(self._moments):
Expand Down Expand Up @@ -1871,7 +1871,7 @@ def insert_into_range(self, operations: 'cirq.OP_TREE', start: int, end: int) ->
IndexError: Bad inline_start and/or inline_end.
"""
if not 0 <= start <= end <= len(self):
raise IndexError('Bad insert indices: [{}, {})'.format(start, end))
raise IndexError(f'Bad insert indices: [{start}, {end})')

flat_ops = list(ops.flatten_to_ops(operations))
for op in flat_ops:
Expand Down Expand Up @@ -2048,7 +2048,7 @@ def batch_remove(self, removals: Iterable[Tuple[int, 'cirq.Operation']]) -> None
copy = self.copy()
for i, op in removals:
if op not in copy._moments[i].operations:
raise ValueError("Can't remove {} @ {} because it doesn't exist.".format(op, i))
raise ValueError(f"Can't remove {op} @ {i} because it doesn't exist.")
copy._moments[i] = ops.Moment(
old_op for old_op in copy._moments[i].operations if op != old_op
)
Expand Down Expand Up @@ -2302,7 +2302,7 @@ def _formatted_phase(coefficient: complex, unicode: bool, precision: Optional[in
unit = 'π' if unicode else 'pi'
if h == 1:
return unit
return '{{:.{}}}'.format(precision).format(h) + unit
return f'{{:.{precision}}}'.format(h) + unit


def _draw_moment_groups_in_diagram(
Expand Down Expand Up @@ -2368,7 +2368,7 @@ def _apply_unitary_circuit(
buffer = np.empty_like(state)

def on_stuck(bad_op):
return TypeError('Operation without a known matrix or decomposition: {!r}'.format(bad_op))
return TypeError(f'Operation without a known matrix or decomposition: {bad_op!r}')

unitary_ops = protocols.decompose(
circuit.all_operations(),
Expand All @@ -2391,7 +2391,7 @@ def _decompose_measurement_inversions(op: 'cirq.Operation') -> 'cirq.OP_TREE':
def _list_repr_with_indented_item_lines(items: Sequence[Any]) -> str:
block = '\n'.join([repr(op) + ',' for op in items])
indented = ' ' + '\n '.join(block.split('\n'))
return '[\n{}\n]'.format(indented)
return f'[\n{indented}\n]'


TIn = TypeVar('TIn')
Expand Down
2 changes: 1 addition & 1 deletion cirq/circuits/circuit_dag.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __init__(self, val: T) -> None:
self.val = val

def __repr__(self) -> str:
return 'cirq.Unique({}, {!r})'.format(id(self), self.val)
return f'cirq.Unique({id(self)}, {self.val!r})'

def __lt__(self, other):
if not isinstance(other, type(self)):
Expand Down
33 changes: 19 additions & 14 deletions cirq/circuits/circuit_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@
class _MomentAndOpTypeValidatingDeviceType(cirq.Device):
def validate_operation(self, operation):
if not isinstance(operation, cirq.Operation):
raise ValueError('not isinstance({!r}, {!r})'.format(operation, cirq.Operation))
raise ValueError(f'not isinstance({operation!r}, {cirq.Operation!r})')

def validate_moment(self, moment):
if not isinstance(moment, cirq.Moment):
raise ValueError('not isinstance({!r}, {!r})'.format(moment, cirq.Moment))
raise ValueError(f'not isinstance({moment!r}, {cirq.Moment!r})')


moment_and_op_type_validating_device = _MomentAndOpTypeValidatingDeviceType()
Expand Down Expand Up @@ -605,15 +605,15 @@ def validate_operation(self, operation: cirq.Operation) -> None:
# This is pretty close to what the cirq.google.XmonDevice has for validation
for q in operation.qubits:
if not isinstance(q, self.allowed_qubit_types):
raise ValueError("Unsupported qubit type: {!r}".format(type(q)))
raise ValueError(f"Unsupported qubit type: {type(q)!r}")
if q not in self.qubits:
raise ValueError('Qubit not on device: {!r}'.format(q))
raise ValueError(f'Qubit not on device: {q!r}')
if not isinstance(operation.gate, self.allowed_gates):
raise ValueError("Unsupported gate type: {!r}".format(operation.gate))
raise ValueError(f"Unsupported gate type: {operation.gate!r}")
if len(operation.qubits) == 2 and not isinstance(operation.gate, ops.MeasurementGate):
p, q = operation.qubits
if not cast(cirq.GridQubit, p).is_adjacent(q):
raise ValueError('Non-local interaction: {!r}.'.format(operation))
raise ValueError(f'Non-local interaction: {operation!r}.')

def decompose_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE':
# a fake decomposer for only TOFFOLI gates
Expand Down Expand Up @@ -1213,6 +1213,9 @@ def test_next_moment_operating_on_distance(circuit_cls):
# Huge max distances should be handled quickly due to capping.
assert c.next_moment_operating_on([a], 5, max_distance=10 ** 100) is None

with pytest.raises(ValueError, match='Negative max_distance'):
c.next_moment_operating_on([a], 0, max_distance=-1)


@pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit])
def test_prev_moment_operating_on(circuit_cls):
Expand Down Expand Up @@ -1258,6 +1261,9 @@ def test_prev_moment_operating_on(circuit_cls):
assert c.prev_moment_operating_on([a, b], 1) == 0
assert c.prev_moment_operating_on([a, b], 0) is None

with pytest.raises(ValueError, match='Negative max_distance'):
assert c.prev_moment_operating_on([a, b], 4, max_distance=-1)


@pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit])
def test_prev_moment_operating_on_distance(circuit_cls):
Expand Down Expand Up @@ -1296,6 +1302,9 @@ def test_prev_moment_operating_on_distance(circuit_cls):
# Huge max distances should be handled quickly due to capping.
assert c.prev_moment_operating_on([a], 1, max_distance=10 ** 100) is None

with pytest.raises(ValueError, match='Negative max_distance'):
c.prev_moment_operating_on([a], 6, max_distance=-1)


@pytest.mark.parametrize('circuit_cls', [cirq.Circuit, cirq.FrozenCircuit])
def test_operation_at(circuit_cls):
Expand Down Expand Up @@ -3535,7 +3544,7 @@ def test_to_qasm(circuit_cls):
assert circuit.to_qasm() == cirq.qasm(circuit)
assert (
circuit.to_qasm()
== """// Generated from Cirq v{}
== f"""// Generated from Cirq v{cirq.__version__}
OPENQASM 2.0;
include "qelib1.inc";
Expand All @@ -3546,9 +3555,7 @@ def test_to_qasm(circuit_cls):
x q[0];
""".format(
cirq.__version__
)
"""
)


Expand All @@ -3565,7 +3572,7 @@ def test_save_qasm(tmpdir, circuit_cls):
file_content = f.read()
assert (
file_content
== """// Generated from Cirq v{}
== f"""// Generated from Cirq v{cirq.__version__}
OPENQASM 2.0;
include "qelib1.inc";
Expand All @@ -3576,9 +3583,7 @@ def test_save_qasm(tmpdir, circuit_cls):
x q[0];
""".format(
cirq.__version__
)
"""
)


Expand Down
24 changes: 11 additions & 13 deletions cirq/circuits/qasm_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
yield QasmUGate.from_matrix(a1).on(q1)

def __repr__(self) -> str:
return 'cirq.circuits.qasm_output.QasmTwoQubitGate({!r})'.format(self.kak)
return f'cirq.circuits.qasm_output.QasmTwoQubitGate({self.kak!r})'


class QasmOutput:
Expand Down Expand Up @@ -192,18 +192,18 @@ def _generate_measurement_ids(self) -> Tuple[Dict[str, str], Dict[str, Optional[
key = protocols.measurement_key(meas)
if key in meas_key_id_map:
continue
meas_id = 'm_{}'.format(key)
meas_id = f'm_{key}'
if self.is_valid_qasm_id(meas_id):
meas_comments[key] = None
else:
meas_id = 'm{}'.format(meas_i)
meas_id = f'm{meas_i}'
meas_i += 1
meas_comments[key] = ' '.join(key.split('\n'))
meas_key_id_map[key] = meas_id
return meas_key_id_map, meas_comments

def _generate_qubit_ids(self) -> Dict['cirq.Qid', str]:
return {qubit: 'q[{}]'.format(i) for i, qubit in enumerate(self.qubits)}
return {qubit: f'q[{i}]' for i, qubit in enumerate(self.qubits)}

def is_valid_qasm_id(self, id_str: str) -> bool:
"""Test if id_str is a valid id in QASM grammar."""
Expand Down Expand Up @@ -255,9 +255,9 @@ def output(text):

# Register definitions
# Qubit registers
output('// Qubits: [{}]\n'.format(', '.join(map(str, self.qubits))))
output(f"// Qubits: [{', '.join(map(str, self.qubits))}]\n")
if len(self.qubits) > 0:
output('qreg q[{}];\n'.format(len(self.qubits)))
output(f'qreg q[{len(self.qubits)}];\n')
# Classical registers
# Pick an id for the creg that will store each measurement
already_output_keys: Set[str] = set()
Expand All @@ -269,11 +269,9 @@ def output(text):
meas_id = self.args.meas_key_id_map[key]
comment = self.meas_comments[key]
if comment is None:
output('creg {}[{}];\n'.format(meas_id, len(meas.qubits)))
output(f'creg {meas_id}[{len(meas.qubits)}];\n')
else:
output(
'creg {}[{}]; // Measurement: {}\n'.format(meas_id, len(meas.qubits), comment)
)
output(f'creg {meas_id}[{len(meas.qubits)}]; // Measurement: {comment}\n')
output_line_gap(2)

# Operations
Expand Down Expand Up @@ -301,7 +299,7 @@ def fallback(op):
return QasmTwoQubitGate.from_matrix(mat).on(*op.qubits)

def on_stuck(bad_op):
return ValueError('Cannot output operation as QASM: {!r}'.format(bad_op))
return ValueError(f'Cannot output operation as QASM: {bad_op!r}')

for main_op in ops.flatten_op_tree(op_tree):
decomposed = protocols.decompose(
Expand All @@ -315,10 +313,10 @@ def on_stuck(bad_op):
output_line_gap(1)
if isinstance(main_op, ops.GateOperation):
x = str(main_op.gate).replace('\n', '\n //')
output('// Gate: {!s}\n'.format(x))
output(f'// Gate: {x!s}\n')
else:
x = str(main_op).replace('\n', '\n //')
output('// Operation: {!s}\n'.format(x))
output(f'// Operation: {x!s}\n')

for qasm in qasms:
output(qasm)
Expand Down
2 changes: 1 addition & 1 deletion cirq/circuits/qasm_output_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@


def _make_qubits(n):
return [cirq.NamedQubit('q{}'.format(i)) for i in range(n)]
return [cirq.NamedQubit(f'q{i}') for i in range(n)]


def test_u_gate_repr():
Expand Down

0 comments on commit 7a335e3

Please sign in to comment.