Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Use a context manager for opening files #219

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ repos:
- id: debug-statements

- repo: https://github.com/crate-ci/typos
rev: v1.23.6
rev: v1.23.7
hooks:
- id: typos

Expand All @@ -25,7 +25,7 @@ repos:
- black==23.10.1

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.1
rev: v0.6.2
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
Expand Down
13 changes: 4 additions & 9 deletions pytket/phir/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
# mypy: disable-error-code="misc"

import logging
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING

Expand Down Expand Up @@ -90,22 +89,18 @@ def qasm_to_phir(
"""
circuit: Circuit
if wasm_bytes:
try:
qasm_file = NamedTemporaryFile(suffix=".qasm", delete=False)
wasm_file = NamedTemporaryFile(suffix=".wasm", delete=False)
with (
NamedTemporaryFile(suffix=".qasm", delete=False) as qasm_file,
NamedTemporaryFile(suffix=".wasm", delete=False) as wasm_file,
Copy link
Member Author

@qartik qartik Aug 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not obvious to me if we need delete=False anymore. See https://docs.python.org/3.11/library/tempfile.html#tempfile.NamedTemporaryFile

On Python 3.12 onward, there is a new parameter called delete_on_close that is preferable here:

Therefore to use the name of the temporary file to reopen the file after closing it, either make sure not to delete the file upon closure (set the delete parameter to be false) or, in case the temporary file is created in a with statement, set the delete_on_close parameter to be false.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps @neal-erickson might have insight about why delete=False was needed?

):
qasm_file.write(qasm.encode())
qasm_file.flush()
qasm_file.close()
wasm_file.write(wasm_bytes)
wasm_file.flush()
wasm_file.close()

circuit = circuit_from_qasm_wasm(
qasm_file.name, wasm_file.name, maxwidth=WORDSIZE
)
finally:
Path.unlink(Path(qasm_file.name))
Path.unlink(Path(wasm_file.name))
else:
circuit = circuit_from_qasm_str(qasm, maxwidth=WORDSIZE)
return pytket_to_phir(circuit, qtm_machine)
5 changes: 2 additions & 3 deletions pytket/phir/rebasing/rebaser.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@

from typing import TYPE_CHECKING

from pytket.passes import DecomposeBoxes
from pytket.passes.auto_rebase import auto_rebase_pass
from pytket.passes import AutoRebase, DecomposeBoxes
from pytket.phir.qtm_machine import QTM_DEFAULT_GATESET, QTM_MACHINES_MAP, QtmMachine

if TYPE_CHECKING:
Expand All @@ -22,5 +21,5 @@ def rebase_to_qtm_machine(circuit: "Circuit", qtm_machine: QtmMachine) -> "Circu
gateset = QTM_DEFAULT_GATESET if machine is None else machine.gateset
c = circuit.copy()
DecomposeBoxes().apply(c)
auto_rebase_pass(gateset, allow_swaps=True).apply(c)
AutoRebase(gateset, allow_swaps=True).apply(c)
return c
5 changes: 2 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ phir==0.3.3
pre-commit==3.8.0
pydata_sphinx_theme==0.15.4
pytest==8.3.2
pytest-order==1.2.1
pytket==1.31.1
ruff==0.6.1
ruff==0.6.2
setuptools_scm==8.1.0
sphinx==8.0.2
wasmtime==23.0.0
wasmtime==24.0.0
wheel==0.44.0
3 changes: 0 additions & 3 deletions tests/test_parallelization.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@

import logging

import pytest

from .test_utils import QasmFile, get_phir_json

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -158,7 +156,6 @@ def test_two_qubit_exec_order_preserved() -> None:
}


@pytest.mark.order("first")
def test_group_ordering() -> None:
"""Test that groups are in the right order when the group number can decrement."""
phir = get_phir_json(QasmFile.group_ordering, rebase=True)
Expand Down
20 changes: 3 additions & 17 deletions tests/test_wasm.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import hashlib
import json
import logging
from pathlib import Path
from tempfile import NamedTemporaryFile

import pytest
Expand Down Expand Up @@ -85,16 +84,13 @@ def test_qasm_wasm_unsupported_reg_len() -> None:
qasm_to_phir(qasm, QtmMachine.H1, wasm_bytes=wasm_bytes)


@pytest.mark.order("first")
def test_pytket_with_wasm() -> None:
"""Test whether pytket works with WASM."""
wasm_bytes = get_wat_as_wasm_bytes(WatFile.testfile)
phir_str: str
try:
wasm_file = NamedTemporaryFile(suffix=".wasm", delete=False)
with NamedTemporaryFile(suffix=".wasm", delete=False) as wasm_file:
wasm_file.write(wasm_bytes)
wasm_file.flush()
wasm_file.close()

w = WasmFileHandler(wasm_file.name)

Expand All @@ -111,8 +107,6 @@ def test_pytket_with_wasm() -> None:
c.add_wasm_to_reg("add_one", w, [c0], [c0], condition=c1[0])

phir_str = pytket_to_phir(c, QtmMachine.H1)
finally:
Path.unlink(Path(wasm_file.name))

phir = json.loads(phir_str)

Expand Down Expand Up @@ -166,11 +160,9 @@ def test_pytket_with_wasm() -> None:
def test_pytket_wasm_unsupported_reg_len() -> None:
"""Test that pytket circuit calling WASM with more than 32-bits fails."""
wasm_bytes = get_wat_as_wasm_bytes(WatFile.testfile)
try:
wasm_file = NamedTemporaryFile(suffix=".wasm", delete=False)
with NamedTemporaryFile(suffix=".wasm", delete=False) as wasm_file:
wasm_file.write(wasm_bytes)
wasm_file.flush()
wasm_file.close()

w = WasmFileHandler(wasm_file.name)

Expand All @@ -179,18 +171,14 @@ def test_pytket_wasm_unsupported_reg_len() -> None:

with pytest.raises(ValueError, match="only registers of at most 32 bits"):
c.add_wasm_to_reg("no_return", w, [c0], [])
finally:
Path.unlink(Path(wasm_file.name))


def test_conditional_wasm() -> None:
"""From https://github.com/CQCL/pytket-phir/issues/156 ."""
wasm_bytes = get_wat_as_wasm_bytes(WatFile.testfile)
try:
wasm_file = NamedTemporaryFile(suffix=".wasm", delete=False)
with NamedTemporaryFile(suffix=".wasm", delete=False) as wasm_file:
wasm_file.write(wasm_bytes)
wasm_file.flush()
wasm_file.close()

w = WasmFileHandler(wasm_file.name)

Expand All @@ -209,8 +197,6 @@ def test_conditional_wasm() -> None:
condition_bits=[breg[0]],
condition_value=1,
)
finally:
Path.unlink(Path(wasm_file.name))

phir = json.loads(pytket_to_phir(c))

Expand Down