Skip to content

Commit db22da2

Browse files
authored
MAINT: fix docstrings for /common and /datasets (microsoft#1193)
1 parent aad228e commit db22da2

34 files changed

Lines changed: 237 additions & 36 deletions

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ extend-select = [
251251
# Temporary ignores for pyrit/ subdirectories until issue #1176
252252
# https://github.com/Azure/PyRIT/issues/1176 is fully resolved
253253
# TODO: Remove these ignores once the issues are fixed
254-
"pyrit/{analytics,auth,auxiliary_attacks,chat_message_normalizer,cli,common,datasets,embedding,exceptions,executor,memory,models,prompt_converter,prompt_normalizer,prompt_target,scenarios,score,setup,ui}/**/*.py" = ["D101", "D102", "D103", "D104", "D105", "D106", "D107", "D401", "D404", "D417", "D418", "DOC102", "DOC201", "DOC202", "DOC402", "DOC501"]
254+
"pyrit/{analytics,auth,auxiliary_attacks,chat_message_normalizer,cli,embedding,exceptions,executor,memory,models,prompt_converter,prompt_normalizer,prompt_target,scenarios,score,setup,ui}/**/*.py" = ["D101", "D102", "D103", "D104", "D105", "D106", "D107", "D401", "D404", "D417", "D418", "DOC102", "DOC201", "DOC202", "DOC402", "DOC501"]
255255
"pyrit/__init__.py" = ["D104"]
256256

257257
[tool.ruff.lint.pydocstyle]

pyrit/common/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Copyright (c) Microsoft Corporation.
22
# Licensed under the MIT license.
33

4-
"""This module contains common utilities for PyRIT."""
4+
"""Common utilities and helpers for PyRIT."""
55

66
from pyrit.common.apply_defaults import (
77
apply_defaults,

pyrit/common/apply_defaults.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,12 @@ class DefaultValueScope:
6262
include_subclasses: bool = True
6363

6464
def __hash__(self) -> int:
65+
"""
66+
Return a hash based on class type, parameter name, and subclass inclusion flag.
67+
68+
Returns:
69+
int: Hash value for this scope.
70+
"""
6571
return hash((self.class_type, self.parameter_name, self.include_subclasses))
6672

6773

@@ -74,6 +80,7 @@ class GlobalDefaultValues:
7480
"""
7581

7682
def __init__(self) -> None:
83+
"""Initialize the global default values registry."""
7784
self._default_values: Dict[DefaultValueScope, Any] = {}
7885

7986
def set_default_value(
@@ -153,7 +160,12 @@ def all_defaults(self) -> Dict[DefaultValueScope, Any]:
153160

154161

155162
def get_global_default_values() -> GlobalDefaultValues:
156-
"""Get the global default values registry."""
163+
"""
164+
Get the global default values registry.
165+
166+
Returns:
167+
GlobalDefaultValues: The global default values registry instance.
168+
"""
157169
return _global_default_values
158170

159171

@@ -221,7 +233,7 @@ def set_global_variable(*, name: str, value: Any) -> None:
221233

222234
def apply_defaults_to_method(method):
223235
"""
224-
Decorator that applies default values to a method's parameters.
236+
Apply default values to a method's parameters.
225237
226238
This decorator looks up default values for the method's class and applies them
227239
to parameters that are None or not provided.
@@ -283,7 +295,7 @@ def wrapper(self, *args, **kwargs):
283295

284296
def apply_defaults(method):
285297
"""
286-
Decorator that applies default values to a class constructor.
298+
Apply default values to a class constructor.
287299
288300
This is an alias for apply_defaults_to_method for backward compatibility.
289301

pyrit/common/csv_helper.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,24 @@
66

77

88
def read_csv(file) -> List[Dict[str, str]]:
9+
"""
10+
Read a CSV file and return its rows as dictionaries.
11+
12+
Returns:
13+
List[Dict[str, str]]: Parsed CSV rows as dictionaries.
14+
"""
915
reader = csv.DictReader(file)
1016
return [row for row in reader]
1117

1218

1319
def write_csv(file, examples: List[Dict[str, str]]):
20+
"""
21+
Write a list of dictionaries to a CSV file.
22+
23+
Args:
24+
file: A file-like object opened for writing CSV data.
25+
examples (List[Dict[str, str]]): List of dictionaries to write as CSV rows.
26+
"""
1427
writer = csv.DictWriter(file, fieldnames=examples[0].keys())
1528
writer.writeheader()
1629
writer.writerows(examples)

pyrit/common/data_url_converter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
async def convert_local_image_to_data_url(image_path: str) -> str:
1212
"""
13-
Converts a local image file to a data URL encoded in base64.
13+
Convert a local image file to a data URL encoded in base64.
1414
1515
Args:
1616
image_path (str): The file system path to the image file.

pyrit/common/default_values.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
def get_required_value(*, env_var_name: str, passed_value: str) -> str:
1212
"""
13-
Gets a required value from an environment variable or a passed value,
13+
Get a required value from an environment variable or a passed value,
1414
preferring the passed value.
1515
1616
If no value is found, raises a KeyError
@@ -37,7 +37,7 @@ def get_required_value(*, env_var_name: str, passed_value: str) -> str:
3737

3838
def get_non_required_value(*, env_var_name: str, passed_value: Optional[str] = None) -> str:
3939
"""
40-
Gets a non-required value from an environment variable or a passed value,
40+
Get a non-required value from an environment variable or a passed value,
4141
preferring the passed value.
4242
4343
Args:

pyrit/common/display_response.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
async def display_image_response(response_piece: MessagePiece) -> None:
1616
"""
17-
Displays response images if running in notebook environment.
17+
Display response images if running in notebook environment.
1818
1919
Args:
2020
response_piece (MessagePiece): The response piece to display.

pyrit/common/download_hf_model.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,15 @@
1313

1414

1515
def get_available_files(model_id: str, token: str):
16-
"""Fetches available files for a model from the Hugging Face repository."""
16+
"""
17+
Fetch available files for a model from the Hugging Face repository.
18+
19+
Returns:
20+
List of available file names.
21+
22+
Raises:
23+
ValueError: If no files are found for the model.
24+
"""
1725
api = HfApi()
1826
try:
1927
model_info = api.model_info(model_id, token=token)
@@ -31,11 +39,8 @@ def get_available_files(model_id: str, token: str):
3139

3240
async def download_specific_files(model_id: str, file_patterns: list, token: str, cache_dir: Path):
3341
"""
34-
Downloads specific files from a Hugging Face model repository.
42+
Download specific files from a Hugging Face model repository.
3543
If file_patterns is None, downloads all files.
36-
37-
Returns:
38-
List of URLs for the downloaded files.
3944
"""
4045
os.makedirs(cache_dir, exist_ok=True)
4146

@@ -60,7 +65,12 @@ async def download_specific_files(model_id: str, file_patterns: list, token: str
6065

6166

6267
async def download_chunk(url, headers, start, end, client):
63-
"""Download a chunk of the file with a specified byte range."""
68+
"""
69+
Download a chunk of the file with a specified byte range.
70+
71+
Returns:
72+
The content of the downloaded chunk.
73+
"""
6474
range_header = {"Range": f"bytes={start}-{end}", **headers}
6575
response = await client.get(url, headers=range_header)
6676
response.raise_for_status()

pyrit/common/json_helper.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,43 @@
66

77

88
def read_json(file) -> List[Dict[str, str]]:
9+
"""
10+
Read a JSON file and return its content.
11+
12+
Returns:
13+
List[Dict[str, str]]: Parsed JSON content.
14+
"""
915
return json.load(file)
1016

1117

1218
def write_json(file, examples: List[Dict[str, str]]):
19+
"""
20+
Write a list of dictionaries to a JSON file.
21+
22+
Args:
23+
file: A file-like object opened for writing JSON data.
24+
examples (List[Dict[str, str]]): List of dictionaries to write as JSON.
25+
"""
1326
json.dump(examples, file)
1427

1528

1629
def read_jsonl(file) -> List[Dict[str, str]]:
30+
"""
31+
Read a JSONL file and return its content.
32+
33+
Returns:
34+
List[Dict[str, str]]: Parsed JSONL content.
35+
"""
1736
return [json.loads(line) for line in file]
1837

1938

2039
def write_jsonl(file, examples: List[Dict[str, str]]):
40+
"""
41+
Write a list of dictionaries to a JSONL file.
42+
43+
Args:
44+
file: A file-like object opened for writing JSONL data.
45+
examples (List[Dict[str, str]]): List of dictionaries to write as JSONL.
46+
"""
2147
for example in examples:
2248
file.write(json.dumps(example) + "\n")

pyrit/common/net_utility.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@
99

1010

1111
def get_httpx_client(use_async: bool = False, debug: bool = False, **httpx_client_kwargs: Optional[Any]):
12-
"""Get the httpx client for making requests."""
12+
"""
13+
Get the httpx client for making requests.
14+
15+
Returns:
16+
httpx.Client or httpx.AsyncClient: The configured httpx client.
17+
"""
1318
client_class = httpx.AsyncClient if use_async else httpx.Client
1419
proxy = "http://localhost:8080" if debug else None
1520

@@ -82,6 +87,9 @@ async def make_request_and_raise_if_error_async(
8287
1. In the endpoint_uri (e.g., "https://api.com/endpoint?api-version=2024-10-21")
8388
2. Via the extra_url_parameters dict
8489
3. Both (extra_url_parameters will be merged with URL query parameters, with extra_url_parameters taking precedence)
90+
91+
Returns:
92+
httpx.Response: The response from the request.
8593
"""
8694
headers = headers or {}
8795
request_body = request_body or {}

0 commit comments

Comments
 (0)