diff --git a/cirq-aqt/setup.py b/cirq-aqt/setup.py
index 9a5ce84ee35..a45b57e2f29 100644
--- a/cirq-aqt/setup.py
+++ b/cirq-aqt/setup.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import pathlib
import runpy
from setuptools import find_packages, setup
@@ -27,8 +28,7 @@
)
# README file as long_description.
-with open('README.md', encoding='utf-8') as file:
- long_description = file.read()
+long_description = pathlib.Path('README.md').read_text(encoding='utf-8')
# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
diff --git a/cirq-core/cirq/circuits/circuit.py b/cirq-core/cirq/circuits/circuit.py
index 845e1e0a476..76be2c2330b 100644
--- a/cirq-core/cirq/circuits/circuit.py
+++ b/cirq-core/cirq/circuits/circuit.py
@@ -587,8 +587,7 @@ def enqueue_next(qubit: cirq.Qid, moment: int) -> None:
next_moment = self.next_moment_operating_on([qubit], moment)
if next_moment is None:
end_frontier[qubit] = max(len(self), start_frontier[qubit])
- if qubit in active:
- active.remove(qubit)
+ active.discard(qubit)
else:
next_op = self.operation_at(qubit, next_moment)
assert next_op is not None
diff --git a/cirq-core/cirq/circuits/circuit_test.py b/cirq-core/cirq/circuits/circuit_test.py
index af335a9cff2..6c3717999da 100644
--- a/cirq-core/cirq/circuits/circuit_test.py
+++ b/cirq-core/cirq/circuits/circuit_test.py
@@ -16,6 +16,7 @@
import itertools
import os
+import pathlib
import time
from collections import defaultdict
from collections.abc import Iterator, Sequence
@@ -3670,8 +3671,7 @@ def test_save_qasm(tmpdir, circuit_cls) -> None:
circuit = circuit_cls(cirq.X(q0))
circuit.save_qasm(file_path)
- with open(file_path, 'r') as f:
- file_content = f.read()
+ file_content = pathlib.Path(file_path).read_text()
assert file_content == f"""// Generated from Cirq v{cirq.__version__}
OPENQASM 2.0;
diff --git a/cirq-core/cirq/circuits/optimization_pass.py b/cirq-core/cirq/circuits/optimization_pass.py
index 921fa697ed8..e31110950f8 100644
--- a/cirq-core/cirq/circuits/optimization_pass.py
+++ b/cirq-core/cirq/circuits/optimization_pass.py
@@ -155,10 +155,9 @@ def optimize_circuit(self, circuit: cirq.Circuit) -> None:
flat_new_operations = tuple(ops.flatten_to_ops(new_operations))
- new_qubits = set()
+ new_qubits: set[cirq.Qid] = set()
for flat_op in flat_new_operations:
- for q in flat_op.qubits:
- new_qubits.add(q)
+ new_qubits.update(flat_op.qubits)
if not new_qubits.issubset(opt.clear_qubits):
raise ValueError(
diff --git a/cirq-core/cirq/circuits/qasm_output_test.py b/cirq-core/cirq/circuits/qasm_output_test.py
index 435409dc87d..f6fb2e94d41 100644
--- a/cirq-core/cirq/circuits/qasm_output_test.py
+++ b/cirq-core/cirq/circuits/qasm_output_test.py
@@ -15,6 +15,7 @@
from __future__ import annotations
import os
+import pathlib
import re
import numpy as np
@@ -265,8 +266,7 @@ def test_save_to_file(tmpdir) -> None:
(q0,) = _make_qubits(1)
output = cirq.QasmOutput((), (q0,))
output.save(file_path)
- with open(file_path, 'r') as f:
- file_content = f.read()
+ file_content = pathlib.Path(file_path).read_text()
assert file_content == """OPENQASM 2.0;
include "qelib1.inc";
diff --git a/cirq-core/cirq/contrib/acquaintance/inspection_utils.py b/cirq-core/cirq/contrib/acquaintance/inspection_utils.py
index 448094589b4..58d77ca4c4c 100644
--- a/cirq-core/cirq/contrib/acquaintance/inspection_utils.py
+++ b/cirq-core/cirq/contrib/acquaintance/inspection_utils.py
@@ -71,9 +71,7 @@ def get_logical_acquaintance_opportunities(
strategy: cirq.Circuit, initial_mapping: LogicalMapping
) -> set[frozenset[int]] | set[frozenset[cirq.Qid]]:
acquaintance_dag = get_acquaintance_dag(strategy, initial_mapping)
- logical_acquaintance_opportunities = set()
- for op in acquaintance_dag.all_operations():
- logical_acquaintance_opportunities.add(
- frozenset(op.logical_indices) # type: ignore[attr-defined]
- )
- return logical_acquaintance_opportunities
+ return {
+ frozenset(op.logical_indices) # type: ignore[attr-defined]
+ for op in acquaintance_dag.all_operations()
+ }
diff --git a/cirq-core/cirq/contrib/paulistring/pauli_string_measurement_with_readout_mitigation.py b/cirq-core/cirq/contrib/paulistring/pauli_string_measurement_with_readout_mitigation.py
index 0f957a305e0..af55e73cb3a 100644
--- a/cirq-core/cirq/contrib/paulistring/pauli_string_measurement_with_readout_mitigation.py
+++ b/cirq-core/cirq/contrib/paulistring/pauli_string_measurement_with_readout_mitigation.py
@@ -588,7 +588,6 @@ def measure_pauli_strings(
normalized_circuits_to_pauli = _normalize_input_paulis(circuits_to_pauli)
# Extract unique qubit tuples from input pauli strings
- unique_qubit_tuples = set()
if measure_on_full_support:
full_support: set[ops.Qid] = set()
for pauli_string_groups in normalized_circuits_to_pauli.values():
@@ -596,11 +595,13 @@ def measure_pauli_strings(
for pauli_string in pauli_strings:
full_support.update(pauli_string.qubits)
# One calibration group
- unique_qubit_tuples.add(tuple(sorted(full_support)))
+ unique_qubit_tuples = {tuple(sorted(full_support))}
else:
- for pauli_string_groups in normalized_circuits_to_pauli.values():
- for pauli_strings in pauli_string_groups:
- unique_qubit_tuples.add(tuple(_extract_readout_qubits(pauli_strings)))
+ unique_qubit_tuples = {
+ tuple(_extract_readout_qubits(pauli_strings))
+ for pauli_string_groups in normalized_circuits_to_pauli.values()
+ for pauli_strings in pauli_string_groups
+ }
# qubits_list is a list of qubit tuples
qubits_list = sorted(unique_qubit_tuples)
diff --git a/cirq-core/cirq/contrib/quantikz/circuit_to_latex_quantikz.py b/cirq-core/cirq/contrib/quantikz/circuit_to_latex_quantikz.py
index 9f6c17ae073..1305b90e53d 100644
--- a/cirq-core/cirq/contrib/quantikz/circuit_to_latex_quantikz.py
+++ b/cirq-core/cirq/contrib/quantikz/circuit_to_latex_quantikz.py
@@ -330,7 +330,7 @@ def _format_exponent_for_display(self, exponent: Any) -> str:
is_symbolic_or_special = any(
char.isalpha()
for char in s_exponent
- if char.lower() not in ["e"] # Exclude 'e' for scientific notation
+ if char.lower() != "e" # Exclude 'e' for scientific notation
)
if not is_symbolic_or_special: # If it looks like a number
try:
@@ -598,10 +598,8 @@ def _generate_latex_body(self) -> str:
active_chunk[i].append(moment_out[i])
moment_out = ["\\qw"] * self.num_qubits
spanned_qubits = set()
- for i in range(min_qubit, max_qubit + 1):
- spanned_qubits.add(i)
- for q in op.qubits:
- spanned_qubits.add(self.qubit_to_index[q])
+ spanned_qubits.update(range(min_qubit, max_qubit + 1))
+ spanned_qubits.update(self.qubit_to_index[q] for q in op.qubits)
op_rnd = self._render_operation(op)
for idx, tex in op_rnd.items():
moment_out[idx] = tex
diff --git a/cirq-core/cirq/ops/phased_x_gate_test.py b/cirq-core/cirq/ops/phased_x_gate_test.py
index a1bc38cd476..849e570711e 100644
--- a/cirq-core/cirq/ops/phased_x_gate_test.py
+++ b/cirq-core/cirq/ops/phased_x_gate_test.py
@@ -261,7 +261,7 @@ def test_exponent_consistency(exponent, phase_exponent) -> None:
"""Verifies that instances of PhasedX gate expose consistent exponents."""
g = cirq.PhasedXPowGate(exponent=exponent, phase_exponent=phase_exponent)
assert g.exponent in [exponent, -exponent]
- assert g.phase_exponent in [cirq.value.canonicalize_half_turns(g.phase_exponent)]
+ assert g.phase_exponent == cirq.value.canonicalize_half_turns(g.phase_exponent)
g2 = cirq.PhasedXPowGate(exponent=g.exponent, phase_exponent=g.phase_exponent)
assert g == g2
diff --git a/cirq-core/cirq/testing/equivalent_basis_map.py b/cirq-core/cirq/testing/equivalent_basis_map.py
index 0d36a683686..d79a0cbb9e3 100644
--- a/cirq-core/cirq/testing/equivalent_basis_map.py
+++ b/cirq-core/cirq/testing/equivalent_basis_map.py
@@ -74,4 +74,4 @@ def _sparse_computational_basis_map(
def _bin_dec(x: int | None, num_bits: int) -> str:
if x is None:
return 'None'
- return f'0b{bin(x)[2:].zfill(num_bits)} ({x})'
+ return f"0b{f'{x:b}'.zfill(num_bits)} ({x})"
diff --git a/cirq-core/setup.py b/cirq-core/setup.py
index f6531c95754..a2251555cf2 100644
--- a/cirq-core/setup.py
+++ b/cirq-core/setup.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import pathlib
import runpy
from setuptools import find_packages, setup
@@ -28,8 +29,7 @@
)
# README file as long_description.
-with open('README.md', encoding='utf-8') as file:
- long_description = file.read()
+long_description = pathlib.Path('README.md').read_text(encoding='utf-8')
# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
diff --git a/cirq-google/setup.py b/cirq-google/setup.py
index e0a18137127..9cedde50236 100644
--- a/cirq-google/setup.py
+++ b/cirq-google/setup.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import pathlib
import runpy
from setuptools import find_packages, setup
@@ -27,8 +28,7 @@
)
# README file as long_description.
-with open('README.md', encoding='utf-8') as file:
- long_description = file.read()
+long_description = pathlib.Path('README.md').read_text(encoding='utf-8')
# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
diff --git a/cirq-ionq/setup.py b/cirq-ionq/setup.py
index 6f77e5689a9..51676fa62ef 100644
--- a/cirq-ionq/setup.py
+++ b/cirq-ionq/setup.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import pathlib
import runpy
from setuptools import find_packages, setup
@@ -25,8 +26,7 @@
description = 'A Cirq package to simulate and connect to IonQ quantum computers'
# README file as long_description.
-with open('README.md', encoding='utf-8') as file:
- long_description = file.read()
+long_description = pathlib.Path('README.md').read_text(encoding='utf-8')
# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
diff --git a/cirq-pasqal/cirq_pasqal/pasqal_qubits_test.py b/cirq-pasqal/cirq_pasqal/pasqal_qubits_test.py
index 5723fa46060..7b98983c81a 100644
--- a/cirq-pasqal/cirq_pasqal/pasqal_qubits_test.py
+++ b/cirq-pasqal/cirq_pasqal/pasqal_qubits_test.py
@@ -39,7 +39,7 @@ def test_pasqal_qubit_ordering_3d():
assert ThreeDQubit(0, 0, 1) >= ThreeDQubit(0, 1, 0)
assert ThreeDQubit(0, 1, 0) >= ThreeDQubit(1, 0, 0)
for i in range(8):
- v = [int(x) for x in bin(i)[2:].zfill(3)]
+ v = [int(x) for x in f'{i:b}'.zfill(3)]
assert ThreeDQubit(0, 0, 0) <= ThreeDQubit(v[0], v[1], v[2])
assert ThreeDQubit(1, 1, 1) >= ThreeDQubit(v[0], v[1], v[2])
diff --git a/cirq-pasqal/cirq_pasqal/pasqal_sampler_test.py b/cirq-pasqal/cirq_pasqal/pasqal_sampler_test.py
index 9baa31a92d6..bb3a3156c25 100644
--- a/cirq-pasqal/cirq_pasqal/pasqal_sampler_test.py
+++ b/cirq-pasqal/cirq_pasqal/pasqal_sampler_test.py
@@ -76,7 +76,7 @@ def test_run_sweep(mock_post, mock_get):
sweep = cirq.Linspace(key='par', start=0.0, stop=1.0, length=2)
num = np.random.randint(0, 2**9)
- binary = bin(num)[2:].zfill(9)
+ binary = f'{num:b}'.zfill(9)
device = cirq_pasqal.PasqalVirtualDevice(control_radius=1, qubits=qs)
ex_circuit = cirq.Circuit()
diff --git a/cirq-pasqal/setup.py b/cirq-pasqal/setup.py
index 8cc4cfc9bf3..a3c6817393e 100644
--- a/cirq-pasqal/setup.py
+++ b/cirq-pasqal/setup.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import pathlib
import runpy
from setuptools import find_packages, setup
@@ -25,8 +26,7 @@
description = 'A Cirq package to simulate and connect to Pasqal quantum computers'
# README file as long_description.
-with open('README.md', encoding='utf-8') as file:
- long_description = file.read()
+long_description = pathlib.Path('README.md').read_text(encoding='utf-8')
# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
diff --git a/cirq-web/cirq_web/widget.py b/cirq-web/cirq_web/widget.py
index 9d051549f9e..cdd188e0737 100644
--- a/cirq-web/cirq_web/widget.py
+++ b/cirq-web/cirq_web/widget.py
@@ -85,8 +85,7 @@ def generate_html_file(
client_code = self.get_client_code()
contents = self._create_html_content(client_code)
path_of_html_file = os.path.join(output_directory, file_name)
- with open(path_of_html_file, 'w', encoding='utf-8') as f:
- f.write(contents)
+ Path(path_of_html_file).write_text(contents, encoding='utf-8')
if open_in_browser:
webbrowser.open(path_of_html_file, new=2)
@@ -118,9 +117,6 @@ def _to_script_tag(bundle_filename: str) -> str:
Returns:
The bundle file as string (readable by browser) wrapped in HTML script tags.
"""
- bundle_file_path = os.path.join(_DIST_PATH, bundle_filename)
- with open(bundle_file_path, 'r', encoding='utf-8') as bundle_file:
- bundle_file_contents = bundle_file.read()
- bundle_html = f''
-
- return bundle_html
+ bundle_file_path = _DIST_PATH.joinpath(bundle_filename)
+ bundle_file_contents = bundle_file_path.read_text(encoding='utf-8')
+ return f''
diff --git a/cirq-web/cirq_web/widget_test.py b/cirq-web/cirq_web/widget_test.py
index 9d02fc8b86f..09142ef7a6a 100644
--- a/cirq-web/cirq_web/widget_test.py
+++ b/cirq-web/cirq_web/widget_test.py
@@ -66,8 +66,7 @@ def test_generate_html_file_with_browser(tmpdir) -> None:
test_widget = FakeWidget()
test_html_path = test_widget.generate_html_file(str(path), 'test.html', open_in_browser=True)
- with open(test_html_path, 'r', encoding='utf-8') as file:
- actual = file.read()
+ actual = Path(test_html_path).read_text(encoding='utf-8')
expected = f"""
diff --git a/cirq-web/setup.py b/cirq-web/setup.py
index b92c492f20d..88b49682b94 100644
--- a/cirq-web/setup.py
+++ b/cirq-web/setup.py
@@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+import pathlib
import runpy
from setuptools import find_packages, setup
@@ -25,8 +26,7 @@
description = 'Web-based 3D visualization tools for Cirq.'
# README file as long_description.
-with open('README.md', encoding='utf-8') as file:
- long_description = file.read()
+long_description = pathlib.Path('README.md').read_text(encoding='utf-8')
# Read in requirements
with open('requirements.txt', encoding='utf-8') as file:
diff --git a/dev_tools/codeowners_test.py b/dev_tools/codeowners_test.py
index 50a678700cc..ad70a5a9771 100644
--- a/dev_tools/codeowners_test.py
+++ b/dev_tools/codeowners_test.py
@@ -15,6 +15,7 @@
from __future__ import annotations
import os
+import pathlib
import pytest
@@ -87,9 +88,9 @@ def test_codeowners(filepath, expected) -> None:
# will be skipped
codeowners = pytest.importorskip("codeowners")
- with open(".github/CODEOWNERS", encoding="utf8") as f:
- owners = codeowners.CodeOwners(f.read())
- assert os.path.exists(
- filepath
- ), f"{filepath} should exist to avoid creating/maintaining meaningless codeowners rules."
- assert set(owners.of(filepath)) == expected
+ owners_text = pathlib.Path(".github/CODEOWNERS").read_text(encoding="utf8")
+ owners = codeowners.CodeOwners(owners_text)
+ assert os.path.exists(
+ filepath
+ ), f"{filepath} should exist to avoid creating/maintaining meaningless codeowners rules."
+ assert set(owners.of(filepath)) == expected
diff --git a/dev_tools/conftest.py b/dev_tools/conftest.py
index 9dccd7677a7..d531114844b 100644
--- a/dev_tools/conftest.py
+++ b/dev_tools/conftest.py
@@ -113,8 +113,7 @@ def _check_for_reuse_or_recreate(env_dir: Path):
def _create_base_env(base_dir: Path, pip_install_args: tuple[str, ...]):
try:
create_virtual_env(str(base_dir), [], sys.executable, True)
- with open(base_dir / "testrun.uid", mode="w", encoding="utf8") as f:
- f.write(testrun_uid)
+ base_dir.joinpath("testrun.uid").write_text(testrun_uid, encoding="utf8")
if pip_install_args:
shell_tools.run([f"{base_dir}/bin/pip", "install", *pip_install_args])
except BaseException as ex:
diff --git a/dev_tools/incremental_coverage.py b/dev_tools/incremental_coverage.py
index f929470b72b..5ecc02bdd53 100644
--- a/dev_tools/incremental_coverage.py
+++ b/dev_tools/incremental_coverage.py
@@ -15,6 +15,7 @@
from __future__ import annotations
import os.path
+import pathlib
import re
from typing import cast
@@ -153,8 +154,7 @@ def get_incremental_uncovered_lines(
touched_lines = diff_to_new_interesting_lines(unified_diff_lines)
- with open(abs_path, 'r', encoding="utf8") as actual_file:
- ignored_lines = determine_ignored_lines(actual_file.read())
+ ignored_lines = determine_ignored_lines(pathlib.Path(abs_path).read_text(encoding="utf8"))
cover_path = abs_path + ',cover'
has_cover_file = os.path.isfile(cover_path)
diff --git a/dev_tools/modules.py b/dev_tools/modules.py
index 0f5f4c7bd1d..c5d774e9c7f 100644
--- a/dev_tools/modules.py
+++ b/dev_tools/modules.py
@@ -201,8 +201,7 @@ def setup(**kwargs):
try:
setuptools.setup = setup
os.chdir(str(folder))
- with open("setup.py", encoding="utf8") as file:
- setup_py = file.read()
+ setup_py = Path("setup.py").read_text(encoding="utf8")
exec(setup_py, globals(), {})
assert setup_args, f"Invalid setup.py - setup() was not called in {folder}/setup.py!"
return setup_args
diff --git a/dev_tools/modules_test.py b/dev_tools/modules_test.py
index e0d47928f53..ad42120ed4c 100644
--- a/dev_tools/modules_test.py
+++ b/dev_tools/modules_test.py
@@ -179,8 +179,7 @@ def test_replace_version_errors() -> None:
@chdir(target_dir=None)
def test_error() -> None:
- with open("setup.py", mode='w') as f:
- f.write('name="test"')
+ Path("setup.py").write_text('name="test"')
with pytest.raises(AssertionError, match=r"Invalid setup.py - setup\(\) was not called.*"):
modules.main(["list", "--mode", "folder", "--include-parent"])
diff --git a/dev_tools/notebooks/isolated_notebook_test.py b/dev_tools/notebooks/isolated_notebook_test.py
index 4fe5ca40c2b..532ce1cf383 100644
--- a/dev_tools/notebooks/isolated_notebook_test.py
+++ b/dev_tools/notebooks/isolated_notebook_test.py
@@ -27,6 +27,7 @@
from __future__ import annotations
import os
+import pathlib
import re
import shutil
import subprocess
@@ -214,22 +215,21 @@ def test_all_notebooks_against_released_cirq(partition, notebook_path, cloned_en
@pytest.mark.parametrize("notebook_path", NOTEBOOKS_DEPENDING_ON_UNRELEASED_FEATURES)
def test_ensure_unreleased_notebooks_install_cirq_pre(notebook_path) -> None:
# utf-8 is important for Windows testing, otherwise characters like ┌──┐ fail on cp1252
- with open(notebook_path, encoding="utf-8") as notebook:
- content = notebook.read()
- mandatory_matches = [
- r"!pip install --upgrade --quiet cirq(-google)?~=1.0.dev",
- (
- r"Note: this notebook relies on unreleased Cirq features\. "
- r"If you want to try these features, make sure you install cirq(-google)? via "
- r"`pip install --upgrade cirq(-google)?~=1.0.dev`\."
- ),
- ]
-
- for m in mandatory_matches:
- assert re.search(m, content), (
- f"{notebook_path} is marked as NOTEBOOKS_DEPENDING_ON_UNRELEASED_FEATURES, "
- f"however it contains no line matching:\n{m}"
- )
+ content = pathlib.Path(notebook_path).read_text(encoding="utf-8")
+ mandatory_matches = [
+ r"!pip install --upgrade --quiet cirq(-google)?~=1.0.dev",
+ (
+ r"Note: this notebook relies on unreleased Cirq features\. "
+ r"If you want to try these features, make sure you install cirq(-google)? via "
+ r"`pip install --upgrade cirq(-google)?~=1.0.dev`\."
+ ),
+ ]
+
+ for m in mandatory_matches:
+ assert re.search(m, content), (
+ f"{notebook_path} is marked as NOTEBOOKS_DEPENDING_ON_UNRELEASED_FEATURES, "
+ f"however it contains no line matching:\n{m}"
+ )
def test_skip_notebooks_has_valid_patterns() -> None:
diff --git a/dev_tools/notebooks/utils_test.py b/dev_tools/notebooks/utils_test.py
index be032fa6660..35fa4a4eec0 100644
--- a/dev_tools/notebooks/utils_test.py
+++ b/dev_tools/notebooks/utils_test.py
@@ -16,6 +16,7 @@
import filecmp
import os
+import pathlib
import shutil
import tempfile
@@ -27,12 +28,10 @@
def write_test_data(ipynb_txt, tst_txt):
directory = tempfile.mkdtemp()
ipynb_path = os.path.join(directory, 'test.ipynb')
- with open(ipynb_path, 'w') as f:
- f.write(ipynb_txt)
+ pathlib.Path(ipynb_path).write_text(ipynb_txt)
tst_path = os.path.join(directory, 'test.tst')
- with open(tst_path, 'w') as f:
- f.write(tst_txt)
+ pathlib.Path(tst_path).write_text(tst_txt)
return directory, ipynb_path
@@ -43,9 +42,8 @@ def test_rewrite_notebook() -> None:
path = dt.rewrite_notebook(ipynb_path)
assert path != ipynb_path
- with open(path, 'r') as f:
- rewritten = f.read()
- assert rewritten == 'd = 3\nd = 4'
+ rewritten = pathlib.Path(path).read_text()
+ assert rewritten == 'd = 3\nd = 4'
os.remove(path)
shutil.rmtree(directory)
@@ -56,9 +54,8 @@ def test_rewrite_notebook_multiple() -> None:
path = dt.rewrite_notebook(ipynb_path)
- with open(path, 'r') as f:
- rewritten = f.read()
- assert rewritten == 'd = 3\nd = 1'
+ rewritten = pathlib.Path(path).read_text()
+ assert rewritten == 'd = 3\nd = 1'
os.remove(path)
shutil.rmtree(directory)
@@ -69,9 +66,8 @@ def test_rewrite_notebook_ignore_non_seperator_lines() -> None:
path = dt.rewrite_notebook(ipynb_path)
- with open(path, 'r') as f:
- rewritten = f.read()
- assert rewritten == 'd = 3\nd = 4'
+ rewritten = pathlib.Path(path).read_text()
+ assert rewritten == 'd = 3\nd = 4'
os.remove(path)
shutil.rmtree(directory)
@@ -80,8 +76,7 @@ def test_rewrite_notebook_ignore_non_seperator_lines() -> None:
def test_rewrite_notebook_no_tst_file() -> None:
directory = tempfile.mkdtemp()
ipynb_path = os.path.join(directory, 'test.ipynb')
- with open(ipynb_path, 'w') as f:
- f.write('d = 5\nd = 4')
+ pathlib.Path(ipynb_path).write_text('d = 5\nd = 4')
path = dt.rewrite_notebook(ipynb_path)
assert path != ipynb_path
diff --git a/dev_tools/snippets_test.py b/dev_tools/snippets_test.py
index 36979f37070..3d9f6c75eed 100644
--- a/dev_tools/snippets_test.py
+++ b/dev_tools/snippets_test.py
@@ -235,8 +235,7 @@ def test_apply_overrides_markdown():
def assert_file_has_working_code_snippets(path: str | pathlib.Path, assume_import: bool):
"""Checks that code snippets in a file actually run."""
- with open(path, encoding='utf-8') as f:
- content = f.read()
+ content = pathlib.Path(path).read_text(encoding='utf-8')
# Find snippets of code, and execute them. They should finish.
overrides = find_markdown_test_overrides(content)
diff --git a/examples/basic_arithmetic.py b/examples/basic_arithmetic.py
index 6edc20c8c61..5200f7ff4f6 100644
--- a/examples/basic_arithmetic.py
+++ b/examples/basic_arithmetic.py
@@ -273,7 +273,7 @@ def main(n=3):
for p in range(2 * 2):
for q in range(2 * 2):
experiment_adder(p, q, n)
- print('')
+ print()
print('Execute Multiplier')
print(cirq.Circuit(cirq.decompose(Multiplier(5 * n).on(*cirq.LineQubit.range(5 * n)))))
for p in range(2 * 2):
diff --git a/pyproject.toml b/pyproject.toml
index c0a08a76af1..02c177b5e48 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -250,14 +250,21 @@ select = [
"F821", # undefined-name, pylint undefined-variable, unexpected-keyword-arg
"F841", # unused-variable, pylint unused-variable
"F901", # raise-not-implemented, pylint notimplemented-raised
+ "FURB101", # read-whole-file
+ "FURB103", # write-whole-file
+ "FURB105", # print-empty-string
+ "FURB116", # f-string-number-format
"FURB131", # delete-full-slice
+ "FURB132", # check-and-remove-from-set
"FURB136", # if-expr-min-max
+ "FURB142", # for-loop-set-mutations
"FURB145", # slice-copy
"FURB148", # unnecessary-enumerate
"FURB166", # int-on-sliced-str
"FURB167", # regex-flag-alias
"FURB168", # isinstance-type-none
"FURB169", # type-none-comparison
+ "FURB171", # single-item-membership-test
"FURB192", # sorted-min-max
"ISC", # flake8-implicit-str-concat
"N804", # invalid-first-argument-name-for-class-method, pylint bad-classmethod-argument
diff --git a/setup.py b/setup.py
index 0359471725e..b2b09c219a2 100644
--- a/setup.py
+++ b/setup.py
@@ -36,8 +36,7 @@
)
# README file as long_description.
-with open('README.md', encoding='utf-8') as file:
- long_description = file.read()
+long_description = pathlib.Path('README.md').read_text(encoding='utf-8')
# This is a pure metapackage that installs all our packages
requirements = [f'{p.name}=={p.version}' for p in modules.list_modules()]