Skip to content

Commit cd9b408

Browse files
committed
Fix pre-commit warnings
1 parent a95f2d0 commit cd9b408

16 files changed

+83
-112
lines changed

.codespell.allow

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ braket
33
te
44
Ket
55
ket
6+
lamda

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ repos:
117117
hooks:
118118
- id: pylint
119119
args: ['--score=n', '--disable=no-member']
120-
additional_dependencies: [pybind11>=2.6, numpy, requests, matplotlib, networkx, qiskit-terra, pyparsing]
120+
additional_dependencies: [pybind11>=2.6, numpy, requests, matplotlib, networkx, pyparsing]
121121

122122
- repo: https://github.com/mgedmin/check-manifest
123123
rev: '0.49'

projectq/backends/_qasm.py

Lines changed: 20 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
# Copyright 2020 ProjectQ-Framework (www.projectq.ch)
32
#
43
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,6 +11,7 @@
1211
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1312
# See the License for the specific language governing permissions and
1413
# limitations under the License.
14+
1515
"""Backend to convert ProjectQ commands to OpenQASM."""
1616

1717
from copy import deepcopy
@@ -57,7 +57,7 @@ def __init__(
5757
"""
5858
Initialize an OpenQASMBackend object.
5959
60-
Contrary to OpenQASM, ProjectQ does not impose the restriction that a programm must start with qubit/bit
60+
Contrary to OpenQASM, ProjectQ does not impose the restriction that a program must start with qubit/bit
6161
allocations and end with some measurements.
6262
6363
The user can configure what happens each time a FlushGate() is encountered by setting the `collate` and
@@ -168,7 +168,7 @@ def _store(self, cmd): # pylint: disable=too-many-branches,too-many-statements
168168
n_controls = get_control_count(cmd)
169169

170170
def _format_angle(angle):
171-
return '({})'.format(angle)
171+
return f'({angle})'
172172

173173
_ccontrolled_gates_func = {
174174
X: 'ccx',
@@ -223,8 +223,8 @@ def _format_angle(angle):
223223
self._creg_dict[qb_id] = self._gen_bit_name(index)
224224

225225
if add:
226-
self._output.append('qubit {};'.format(self._qreg_dict[qb_id]))
227-
self._output.append('bit {};'.format(self._creg_dict[qb_id]))
226+
self._output.append(f'qubit {self._qreg_dict[qb_id]};')
227+
self._output.append(f'bit {self._creg_dict[qb_id]};')
228228

229229
elif gate == Deallocate:
230230
qb_id = cmd.qubits[0][0].id
@@ -238,29 +238,25 @@ def _format_angle(angle):
238238
assert len(cmd.qubits) == 1 and len(cmd.qubits[0]) == 1
239239
qb_id = cmd.qubits[0][0].id
240240

241-
self._output.append('{} = measure {};'.format(self._creg_dict[qb_id], self._qreg_dict[qb_id]))
241+
self._output.append(f'{self._creg_dict[qb_id]} = measure {self._qreg_dict[qb_id]};')
242242

243243
elif n_controls == 2:
244244
targets = [self._qreg_dict[qb.id] for qureg in cmd.qubits for qb in qureg]
245245
controls = [self._qreg_dict[qb.id] for qb in cmd.control_qubits]
246246

247247
try:
248-
self._output.append('{} {};'.format(_ccontrolled_gates_func[gate], ','.join(controls + targets)))
248+
self._output.append(f'{_ccontrolled_gates_func[gate]} {",".join(controls + targets)};')
249249
except KeyError as err:
250-
raise RuntimeError('Unable to perform {} gate with n=2 control qubits'.format(gate)) from err
250+
raise RuntimeError(f'Unable to perform {gate} gate with n=2 control qubits') from err
251251

252252
elif n_controls == 1:
253253
target_qureg = [self._qreg_dict[qb.id] for qureg in cmd.qubits for qb in qureg]
254254

255255
try:
256256
if isinstance(gate, Ph):
257257
self._output.append(
258-
'{}{} {},{};'.format(
259-
_controlled_gates_func[type(gate)],
260-
_format_angle(-gate.angle / 2.0),
261-
self._qreg_dict[cmd.control_qubits[0].id],
262-
target_qureg[0],
263-
)
258+
f'{_controlled_gates_func[type(gate)]}{_format_angle(-gate.angle / 2.0)} '
259+
f'{self._qreg_dict[cmd.control_qubits[0].id]},{target_qureg[0]};'
264260
)
265261
elif isinstance(
266262
gate,
@@ -270,33 +266,27 @@ def _format_angle(angle):
270266
),
271267
):
272268
self._output.append(
273-
'{}{} {},{};'.format(
274-
_controlled_gates_func[type(gate)],
275-
_format_angle(gate.angle),
276-
self._qreg_dict[cmd.control_qubits[0].id],
277-
target_qureg[0],
278-
)
269+
f'{_controlled_gates_func[type(gate)]}{_format_angle(gate.angle)} '
270+
f'{self._qreg_dict[cmd.control_qubits[0].id]},{target_qureg[0]};'
279271
)
280272
else:
281273
self._output.append(
282-
'{} {},{};'.format(
274+
'{} {},{};'.format( # pylint: disable=consider-using-f-string
283275
_controlled_gates_func[gate], self._qreg_dict[cmd.control_qubits[0].id], *target_qureg
284276
)
285277
)
286278
except KeyError as err:
287-
raise RuntimeError('Unable to perform {} gate with n=1 control qubits'.format(gate)) from err
279+
raise RuntimeError(f'Unable to perform {gate} gate with n=1 control qubits') from err
288280
else:
289281
target_qureg = [self._qreg_dict[qb.id] for qureg in cmd.qubits for qb in qureg]
290282
if isinstance(gate, Ph):
291-
self._output.append(
292-
'{}{} {};'.format(_gates_func[type(gate)], _format_angle(-gate.angle / 2.0), target_qureg[0])
293-
)
283+
self._output.append(f'{_gates_func[type(gate)]}{_format_angle(-gate.angle / 2.0)} {target_qureg[0]};')
294284
elif isinstance(gate, (R, Rx, Ry, Rz)):
285+
self._output.append(f'{_gates_func[type(gate)]}{_format_angle(gate.angle)} {target_qureg[0]};')
286+
else:
295287
self._output.append(
296-
'{}{} {};'.format(_gates_func[type(gate)], _format_angle(gate.angle), target_qureg[0])
288+
'{} {};'.format(_gates_func[gate], *target_qureg) # pylint: disable=consider-using-f-string
297289
)
298-
else:
299-
self._output.append('{} {};'.format(_gates_func[gate], *target_qureg))
300290

301291
def _insert_openqasm_header(self):
302292
self._output.append('OPENQASM 3;')
@@ -311,6 +301,6 @@ def _reset_after_flush(self):
311301
self._output.clear()
312302
self._insert_openqasm_header()
313303
for qubit_name in self._qreg_dict.values():
314-
self._output.append('qubit {};'.format(qubit_name))
304+
self._output.append(f'qubit {qubit_name};')
315305
for bit_name in self._creg_dict.values():
316-
self._output.append('bit {};'.format(bit_name))
306+
self._output.append(f'bit {bit_name};')

projectq/backends/_qasm_test.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
# Copyright 2020 ProjectQ-Framework (www.projectq.ch)
32
#
43
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -85,8 +84,8 @@ def test_qasm_allocate_deallocate(qubit_id_redux):
8584
assert not backend._available_indices
8685
qasm = '\n'.join(eng.backend.qasm)
8786
for i in range(1, 6):
88-
assert re.search(r'qubit\s+q{}'.format(i), qasm)
89-
assert re.search(r'bit\s+c{}'.format(i), qasm)
87+
assert re.search(fr'qubit\s+q{i}', qasm)
88+
assert re.search(fr'bit\s+c{i}', qasm)
9089

9190
del qubit
9291
eng.flush()
@@ -394,10 +393,10 @@ def _process(output):
394393

395394
def test_qasm_name_callback():
396395
def _qubit(index):
397-
return 'qubit_{}'.format(index)
396+
return f'qubit_{index}'
398397

399398
def _bit(index):
400-
return 'classical_bit_{}'.format(index)
399+
return f'classical_bit_{index}'
401400

402401
eng = MainEngine(backend=OpenQASMBackend(qubit_callback=_qubit, bit_callback=_bit), engine_list=[])
403402

projectq/libs/qasm/__init__.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
# Copyright 2020 ProjectQ-Framework (www.projectq.ch)
32
#
43
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,9 +11,8 @@
1211
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1312
# See the License for the specific language governing permissions and
1413
# limitations under the License.
15-
"""
16-
Contains functions/classes to handle OpenQASM
17-
"""
14+
15+
"""Contains functions/classes to handle OpenQASM."""
1816

1917
try:
2018
from ._parse_qasm_qiskit import read_qasm_file, read_qasm_str
@@ -28,15 +26,11 @@
2826
)
2927

3028
def read_qasm_file(eng, filename):
31-
"""
32-
Dummy implementation
33-
"""
29+
"""Invalid implementation."""
3430
# pylint: disable=unused-argument
3531
raise RuntimeError(ERROR_MSG)
3632

3733
def read_qasm_str(eng, qasm_str):
38-
"""
39-
Dummy implementation
40-
"""
34+
"""Invalid implementation."""
4135
# pylint: disable=unused-argument
4236
raise RuntimeError(ERROR_MSG)

projectq/libs/qasm/_parse_qasm_pyparsing.py

Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
# Copyright 2020 ProjectQ-Framework (www.projectq.ch)
32
#
43
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -96,7 +95,7 @@ def eval(self, _):
9695

9796
def __repr__(self): # pragma: nocover
9897
"""Mainly for debugging."""
99-
return 'QASMVersionOp({})'.format(self.version)
98+
return f'QASMVersionOp({self.version})'
10099

101100

102101
class IncludeOp:
@@ -121,11 +120,11 @@ def eval(self, _):
121120
if self.fname in 'qelib1.inc, stdlib.inc':
122121
pass
123122
else: # pragma: nocover
124-
raise RuntimeError('Invalid cannot read: {}! (unsupported)'.format(self.fname))
123+
raise RuntimeError(f'Invalid cannot read: {self.fname}! (unsupported)')
125124

126125
def __repr__(self): # pragma: nocover
127126
"""Mainly for debugging."""
128-
return 'IncludeOp({})'.format(self.fname)
127+
return f'IncludeOp({self.fname})'
129128

130129

131130
# ==============================================================================
@@ -162,8 +161,8 @@ def eval(self, _):
162161
def __repr__(self): # pragma: nocover
163162
"""Mainly for debugging."""
164163
if self.index is not None:
165-
return 'Qubit({}[{}])'.format(self.name, self.index)
166-
return 'Qubit({})'.format(self.name)
164+
return f'Qubit({self.name}[{self.index}])'
165+
return f'Qubit({self.name})'
167166

168167

169168
# ==============================================================================
@@ -192,9 +191,9 @@ def __init__(self, type_t, nbits, name, init):
192191
def __repr__(self): # pragma: nocover
193192
"""Mainly for debugging."""
194193
if self.init:
195-
return "{}({}, {}, {}) = {}".format(self.__class__.__name__, self.type_t, self.nbits, self.name, self.init)
194+
return f"{self.__class__.__name__}({self.type_t}, {self.nbits}, {self.name}) = {self.init}"
196195

197-
return "{}({}, {}, {})".format(self.__class__.__name__, self.type_t, self.nbits, self.name)
196+
return f"{self.__class__.__name__}({self.type_t}, {self.nbits}, {self.name})"
198197

199198

200199
# ------------------------------------------------------------------------------
@@ -215,7 +214,7 @@ def eval(self, eng):
215214
if self.name not in _QISKIT_VARS:
216215
_QISKIT_VARS[self.name] = eng.allocate_qureg(self.nbits)
217216
else: # pragma: nocover
218-
raise RuntimeError('Variable exist already: {}'.format(self.name))
217+
raise RuntimeError(f'Variable exist already: {self.name}')
219218

220219

221220
# ------------------------------------------------------------------------------
@@ -240,7 +239,7 @@ def eval(self, _):
240239
if self.init: # pragma: nocover
241240
init = parse_expr(self.init)
242241

243-
# The followings are OpenQASM 3.0
242+
# The following are OpenQASM 3.0
244243
if self.type_t in ('const', 'float', 'fixed', 'angle'): # pragma: nocover
245244
_BITS_VARS[self.name] = float(init)
246245
elif self.type_t in ('int', 'uint'): # pragma: nocover
@@ -252,7 +251,7 @@ def eval(self, _):
252251
assert self.init is None
253252
_BITS_VARS[self.name] = [False] * self.nbits
254253
else: # pragma: nocover
255-
raise RuntimeError('Variable exist already: {}'.format(self.name))
254+
raise RuntimeError(f'Variable exist already: {self.name}')
256255

257256

258257
# ==============================================================================
@@ -286,7 +285,7 @@ def eval(self, _):
286285

287286
def __repr__(self): # pragma: nocover
288287
"""Mainly for debugging."""
289-
return "GateDefOp({}, {}, {})\n\t{}".format(self.name, self.params, self.qparams, self.body)
288+
return f"GateDefOp({self.name}, {self.params}, {self.qparams})\n\t{self.body}"
290289

291290

292291
# ==============================================================================
@@ -323,8 +322,6 @@ def eval(self, eng):
323322
# pylint: disable = pointless-statement, expression-not-assigned
324323
# pylint: disable = global-statement
325324

326-
global _BITS_VARS
327-
328325
qubits = self.qubits.eval(eng)
329326
if not isinstance(qubits, list):
330327
Measure | qubits
@@ -345,7 +342,7 @@ def eval(self, eng):
345342

346343
def __repr__(self): # pragma: nocover
347344
"""Mainly for debugging."""
348-
return 'MeasureOp({}, {})'.format(self.qubits, self.bits)
345+
return f'MeasureOp({self.qubits}, {self.bits})'
349346

350347

351348
# ------------------------------------------------------------------------------
@@ -378,8 +375,8 @@ def eval(self, _):
378375
def __repr__(self): # pragma: nocover
379376
"""Mainly for debugging."""
380377
if self.params:
381-
return 'OpaqueOp({}, {})'.format(self.name, self.params)
382-
return 'OpaqueOp({})'.format(self.name)
378+
return f'OpaqueOp({self.name}, {self.params})'
379+
return f'OpaqueOp({self.name})'
383380

384381

385382
# ------------------------------------------------------------------------------
@@ -388,7 +385,7 @@ def __repr__(self): # pragma: nocover
388385
class GateOp:
389386
"""Gate applied to qubits operation."""
390387

391-
def __init__(self, s, loc, toks):
388+
def __init__(self, string, loc, toks):
392389
"""
393390
Initialize a GateOp object.
394391
@@ -401,7 +398,7 @@ def __init__(self, s, loc, toks):
401398
self.params = []
402399
self.qubits = [QubitProxy(qubit) for qubit in toks[1]]
403400
else:
404-
param_str = s[loc : s.find(';', loc)] # noqa: E203
401+
param_str = string[loc : string.find(';', loc)] # noqa: E203
405402
self.params = param_str[param_str.find('(') + 1 : param_str.rfind(')')].split(',') # noqa: E203
406403
self.qubits = [QubitProxy(qubit) for qubit in toks[2]]
407404

@@ -457,14 +454,14 @@ def eval(self, eng): # pylint: disable=too-many-branches
457454
_BITS_VARS = bits_vars_bak
458455
else: # pragma: nocover
459456
if self.params:
460-
gate_str = '{}({}) | {}'.format(self.name, self.params, self.qubits)
457+
gate_str = f'{self.name}({self.params}) | {self.qubits}'
461458
else:
462-
gate_str = '{} | {}'.format(self.name, self.qubits)
463-
raise RuntimeError('Unknown gate: {}'.format(gate_str))
459+
gate_str = f'{self.name} | {self.qubits}'
460+
raise RuntimeError(f'Unknown gate: {gate_str}')
464461

465462
def __repr__(self): # pragma: nocover
466463
"""Mainly for debugging."""
467-
return 'GateOp({}, {}, {})'.format(self.name, self.params, self.qubits)
464+
return f'GateOp({self.name}, {self.params}, {self.qubits})'
468465

469466

470467
# ==============================================================================
@@ -496,12 +493,12 @@ def eval(self, _):
496493
value = parse_expr(self.value)
497494
_BITS_VARS[self.var] = value
498495
else:
499-
raise RuntimeError('The variable {} is not defined!'.format(self.var))
496+
raise RuntimeError(f'The variable {self.var} is not defined!')
500497
return 0
501498

502499
def __repr__(self):
503500
"""Mainly for debugging."""
504-
return 'AssignOp({},{})'.format(self.var, self.value)
501+
return f'AssignOp({self.var},{self.value})'
505502

506503

507504
# ==============================================================================
@@ -520,7 +517,7 @@ def _parse_if_conditional(if_str):
520517
level -= 1
521518
if level == 0:
522519
return if_str[start : start + idx] # noqa: E203
523-
raise RuntimeError('Unbalanced parantheses in {}'.format(if_str)) # pragma: nocover
520+
raise RuntimeError(f'Unbalanced parentheses in {if_str}') # pragma: nocover
524521

525522

526523
class IfOp:
@@ -584,7 +581,7 @@ def eval(self, eng):
584581

585582
def __repr__(self): # pragma: nocover
586583
"""Mainly for debugging."""
587-
return "IfExpr({} {} {}) {{ {} }}".format(self.bit, self.binary_op, self.comp_expr, self.body)
584+
return f"IfExpr({self.bit} {self.binary_op} {self.comp_expr}) {{ {self.body} }}"
588585

589586

590587
# ==============================================================================

projectq/libs/qasm/_parse_qasm_pyparsing_test.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
# Copyright 2021 <Huawei Technologies Co., Ltd>
32
#
43
# Licensed under the Apache License, Version 2.0 (the "License");

0 commit comments

Comments
 (0)