Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
anthayes92 committed Sep 13, 2024
1 parent 4b339da commit 8986ea0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 23 deletions.
30 changes: 16 additions & 14 deletions pennylane/data/data_manager/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def _get_dataset_urls(class_id: str, parameters: dict[str, list[str]]) -> list[t
]


def _download_dataset( # pylint: disable=too-many-arguments
def _download_dataset( # pylint: disable=too-many-arguments
dataset_url: str,
dest: Path,
attributes: Optional[Iterable[str]],
Expand Down Expand Up @@ -291,9 +291,7 @@ def _validate_attributes(data_name: str, attributes: Iterable[str]):
"""Checks that ``attributes`` contains only valid attributes for the given
``data_name``. If any attributes do not exist, raise a ValueError."""
valid_attributes = list_attributes(data_name)
invalid_attributes = [
attr for attr in attributes if attr not in valid_attributes
]
invalid_attributes = [attr for attr in attributes if attr not in valid_attributes]
if not invalid_attributes:
return

Expand Down Expand Up @@ -540,8 +538,11 @@ def _interactive_request_data_name(data_names):

def _interactive_request_attributes(attribute_options):
"""Prompt the user to select a list of attributes."""
print(f"Please select a list of attributes from the following available attributes or \"full\" for all attributes.")
for i, option in enumerate(attribute_options): print(f"{i + 1}: {option}")
print(
f'Please select a list of attributes from the following available attributes or "full" for all attributes.'

Check notice on line 542 in pennylane/data/data_manager/__init__.py

View check run for this annotation

codefactor.io / CodeFactor

pennylane/data/data_manager/__init__.py#L542

Using an f-string that does not have any interpolated variables (f-string-without-interpolation)
)
for i, option in enumerate(attribute_options):
print(f"{i + 1}: {option}")
choice = input("Choice of attributes: ")
if choice == "full":

Check notice on line 547 in pennylane/data/data_manager/__init__.py

View check run for this annotation

codefactor.io / CodeFactor

pennylane/data/data_manager/__init__.py#L547

Unnecessary "elif" after "return", remove the leading "el" from "elif" (no-else-return)
return attribute_options
Expand All @@ -555,18 +556,19 @@ def _interactive_requests(parameters, parameter_tree):
choices = []
for param in parameters:
print(f"Avaliable options for {param}:")
for i, option in enumerate(branch["next"].keys()): print(f"{i + 1}: {option}")
for i, option in enumerate(branch["next"].keys()):
print(f"{i + 1}: {option}")
user_value = input(f"Please select a {param}:")
try:
branch = branch["next"][user_value]
except KeyError as e:

Check notice on line 564 in pennylane/data/data_manager/__init__.py

View check run for this annotation

codefactor.io / CodeFactor

pennylane/data/data_manager/__init__.py#L564

Unused variable 'e' (unused-variable)
raise ValueError(f"Must enter a valid {param}:")

Check notice on line 565 in pennylane/data/data_manager/__init__.py

View check run for this annotation

codefactor.io / CodeFactor

pennylane/data/data_manager/__init__.py#L565

Consider explicitly re-raising using 'raise ValueError(f'Must enter a valid {param}:') from e' (raise-missing-from)
choices.append(user_value)
if "next" in branch:

Check notice on line 567 in pennylane/data/data_manager/__init__.py

View check run for this annotation

codefactor.io / CodeFactor

pennylane/data/data_manager/__init__.py#L567

Unnecessary "else" after "continue", remove the "else" and de-indent the code inside it (no-else-continue)
if len(branch['next']) == 1:
if len(branch["next"]) == 1:
branch = next(iter(branch["next"].values()))
continue
else:
else:
branch = branch["value"]
return branch

Expand All @@ -592,10 +594,10 @@ def _get_parameter_tree(class_id) -> tuple[list[str], list[str], dict]:
{"input": {"datasetClassId": class_id}},
)

parameters = [param['name'] for param in response['data']['datasetClass']['parameters']]
attributes = [atr['name'] for atr in response['data']['datasetClass']['attributes']]
parameters = [param["name"] for param in response["data"]["datasetClass"]["parameters"]]
attributes = [atr["name"] for atr in response["data"]["datasetClass"]["attributes"]]

return (parameters, attributes, response['data']['datasetClass']['parameterTree'])
return (parameters, attributes, response["data"]["datasetClass"]["parameterTree"])


def _get_data_names() -> list[str]:
Expand All @@ -608,9 +610,9 @@ def _get_data_names() -> list[str]:
id
}
}
"""
""",
)
return [dsc['id'] for dsc in response['data']['datasetClasses']]
return [dsc["id"] for dsc in response["data"]["datasetClasses"]]


def load_interactive():
Expand Down
30 changes: 21 additions & 9 deletions tests/data/data_manager/test_dataset_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,13 +193,15 @@ class TestLoadInteractive:
@pytest.mark.parametrize(
("side_effect"),
[
(
["qspin", "Heisenberg", "1x4", "open", "full", True, PosixPath("/my/path"), "Y"]
),
(["qspin", "Heisenberg", "1x4", "open", "full", True, PosixPath("/my/path"), "Y"]),
],
)
def test_load_interactive_success(
self, mock_input, mock_sleep, mock_load, side_effect,
self,
mock_input,
mock_sleep,
mock_load,
side_effect,
): # pylint:disable=too-many-arguments, redefined-outer-name
"""Test that load_interactive succeeds."""
mock_input.side_effect = side_effect
Expand All @@ -209,17 +211,26 @@ def test_load_interactive_without_confirm(
self, mock_input, _mock_sleep, mock_load
): # pylint:disable=redefined-outer-name
"""Test that load_interactive returns None if the user doesn't confirm."""
mock_input.side_effect = ["qspin", "Heisenberg", "1x4", "open", "full", True, PosixPath("/my/path"), "n"]
mock_input.side_effect = [
"qspin",
"Heisenberg",
"1x4",
"open",
"full",
True,
PosixPath("/my/path"),
"n",
]
assert qml.data.load_interactive() is None
mock_load.assert_not_called()

@pytest.mark.parametrize(
("side_effect", "error_message"),
[
(["foo"], re.escape("Must select a single data name from ['other', 'qchem', 'qspin']")),
(["qspin", "foo"], 'Must enter a valid sysname:'),
(["qspin", "Ising", "foo"], 'Must enter a valid layout:'),
(["qspin", "Ising", "1x4", "foo"], 'Must enter a valid periodicity:'),
(["qspin", "foo"], "Must enter a valid sysname:"),
(["qspin", "Ising", "foo"], "Must enter a valid layout:"),
(["qspin", "Ising", "1x4", "foo"], "Must enter a valid periodicity:"),
],
)
def test_load_interactive_invalid_inputs(
Expand Down Expand Up @@ -402,13 +413,14 @@ def test_download_dataset_partial_call(download_partial, attributes, force):
pbar_task=pbar_task,
)


@pytest.mark.usefixtures("mock_requests_get")
@pytest.mark.parametrize("mock_requests_get", [b"This is binary data"], indirect=True)
def test_download_full(tmp_path):
"""Tests that _download_dataset will fetch the dataset file
at ``s3_url`` into ``dest``."""
pennylane.data.data_manager._download_full(
f"{GRAPHQL_URL}/dataset/path", tmp_path / "dataset", block_size=1, pbar_task=None
f"{GRAPHQL_URL}/dataset/path", tmp_path / "dataset", block_size=1, pbar_task=None
)

with open(tmp_path / "dataset", "rb") as f:
Expand Down

0 comments on commit 8986ea0

Please sign in to comment.