Skip to content

Commit ed4f181

Browse files
committed
Ruff PTH: moved to pathlib anywhere I could
1 parent fb99768 commit ed4f181

22 files changed

+96
-162
lines changed

duckdb/experimental/spark/sql/types.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1182,9 +1182,7 @@ def __contains__(self, item: Any) -> bool: # noqa: D105, ANN401
11821182
def __call__(self, *args: Any) -> "Row": # noqa: ANN401
11831183
"""Create new Row object."""
11841184
if len(args) > len(self):
1185-
raise ValueError(
1186-
f"Can not create Row with fields {self}, expected {len(self):d} values but got {args}"
1187-
)
1185+
raise ValueError(f"Can not create Row with fields {self}, expected {len(self):d} values but got {args}")
11881186
return _create_row(self, args)
11891187

11901188
def __getitem__(self, item: Any) -> Any: # noqa: D105, ANN401

duckdb/query_graph/__main__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import argparse # noqa: D100
22
import json
3-
import os
43
import re
54
import sys
65
import webbrowser
76
from functools import reduce
7+
from pathlib import Path
88

99
qgraph_css = """
1010
.styled-table {
@@ -122,7 +122,7 @@ def get_sum_of_all_timings(self) -> float: # noqa: D102
122122

123123

124124
def open_utf8(fpath: str, flags: str) -> object: # noqa: D103
125-
return open(fpath, flags, encoding="utf8")
125+
return Path(fpath).open(mode=flags, encoding="utf8")
126126

127127

128128
def get_child_timings(top_node: object, query_timings: object) -> str: # noqa: D103
@@ -355,7 +355,7 @@ def main() -> None: # noqa: D103
355355
translate_json_to_html(input, output)
356356

357357
if open_output:
358-
webbrowser.open("file://" + os.path.abspath(output), new=2)
358+
webbrowser.open(f"file://{Path(output).resolve()}", new=2)
359359

360360

361361
if __name__ == "__main__":

duckdb_packaging/build_backend.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
Also see https://peps.python.org/pep-0517/#in-tree-build-backends.
1414
"""
1515

16-
import os
1716
import subprocess
1817
import sys
1918
from pathlib import Path
@@ -91,7 +90,7 @@ def _duckdb_submodule_path() -> Path:
9190
elif line.strip().startswith("path"):
9291
cur_module_path = line.split("=")[-1].strip()
9392
elif line.strip().startswith("url"):
94-
basename = os.path.basename(line.split("=")[-1].strip())
93+
basename = Path(line.split("=")[-1].strip()).name
9594
cur_module_reponame = basename[:-4] if basename.endswith(".git") else basename
9695
if cur_module_reponame is not None and cur_module_path is not None:
9796
modules[cur_module_reponame] = cur_module_path

scripts/generate_connection_methods.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,7 @@ def is_py_args(method):
3030

3131
def generate():
3232
# Read the PYCONNECTION_SOURCE file
33-
with open(PYCONNECTION_SOURCE) as source_file:
34-
source_code = source_file.readlines()
33+
source_code = Path(PYCONNECTION_SOURCE).read_text().splitlines()
3534

3635
start_index = -1
3736
end_index = -1
@@ -56,8 +55,7 @@ def generate():
5655
# ---- Generate the definition code from the json ----
5756

5857
# Read the JSON file
59-
with open(JSON_PATH) as json_file:
60-
connection_methods = json.load(json_file)
58+
connection_methods = json.loads(Path(JSON_PATH).read_text())
6159

6260
DEFAULT_ARGUMENT_MAP = {
6361
"True": "true",
@@ -127,8 +125,7 @@ def create_definition(name, method) -> str:
127125
new_content = start_section + with_newlines + end_section
128126

129127
# Write out the modified PYCONNECTION_SOURCE file
130-
with open(PYCONNECTION_SOURCE, "w") as source_file:
131-
source_file.write("".join(new_content))
128+
Path(PYCONNECTION_SOURCE).write_text("".join(new_content))
132129

133130

134131
if __name__ == "__main__":

scripts/generate_connection_stubs.py

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

1414
def generate():
1515
# Read the DUCKDB_STUBS_FILE file
16-
with open(DUCKDB_STUBS_FILE) as source_file:
17-
source_code = source_file.readlines()
16+
source_code = Path(DUCKDB_STUBS_FILE).read_text().splitlines()
1817

1918
start_index = -1
2019
end_index = -1
@@ -39,8 +38,7 @@ def generate():
3938
# ---- Generate the definition code from the json ----
4039

4140
# Read the JSON file
42-
with open(JSON_PATH) as json_file:
43-
connection_methods = json.load(json_file)
41+
connection_methods = json.loads(Path(JSON_PATH).read_text())
4442

4543
body = []
4644

@@ -95,8 +93,7 @@ def create_overloaded_definition(name, method) -> str:
9593
new_content = start_section + with_newlines + end_section
9694

9795
# Write out the modified DUCKDB_STUBS_FILE file
98-
with open(DUCKDB_STUBS_FILE, "w") as source_file:
99-
source_file.write("".join(new_content))
96+
Path(DUCKDB_STUBS_FILE).write_text("".join(new_content))
10097

10198

10299
if __name__ == "__main__":

scripts/generate_connection_wrapper_methods.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,7 @@
3939
INIT_PY_END = "# END OF CONNECTION WRAPPER"
4040

4141
# Read the JSON file
42-
with open(WRAPPER_JSON_PATH) as json_file:
43-
wrapper_methods = json.load(json_file)
42+
wrapper_methods = json.loads(Path(WRAPPER_JSON_PATH).read_text())
4443

4544
# On DuckDBPyConnection these are read_only_properties, they're basically functions without requiring () to invoke
4645
# that's not possible on 'duckdb' so it becomes a function call with no arguments (i.e duckdb.description())
@@ -96,20 +95,17 @@ def remove_section(content, start_marker, end_marker) -> tuple[list[str], list[s
9695

9796
def generate():
9897
# Read the DUCKDB_PYTHON_SOURCE file
99-
with open(DUCKDB_PYTHON_SOURCE) as source_file:
100-
source_code = source_file.readlines()
98+
source_code = Path(DUCKDB_PYTHON_SOURCE).read_text().splitlines()
10199
start_section, end_section = remove_section(source_code, START_MARKER, END_MARKER)
102100

103101
# Read the DUCKDB_INIT_FILE file
104-
with open(DUCKDB_INIT_FILE) as source_file:
105-
source_code = source_file.readlines()
102+
source_code = Path(DUCKDB_INIT_FILE).read_text().splitlines()
106103
py_start, py_end = remove_section(source_code, INIT_PY_START, INIT_PY_END)
107104

108105
# ---- Generate the definition code from the json ----
109106

110107
# Read the JSON file
111-
with open(JSON_PATH) as json_file:
112-
connection_methods = json.load(json_file)
108+
connection_methods = json.loads(Path(JSON_PATH).read_text())
113109

114110
# Collect the definitions from the pyconnection.hpp header
115111

@@ -241,8 +237,7 @@ def create_definition(name, method, lambda_def) -> str:
241237
# Recreate the file content by concatenating all the pieces together
242238
new_content = start_section + with_newlines + end_section
243239
# Write out the modified DUCKDB_PYTHON_SOURCE file
244-
with open(DUCKDB_PYTHON_SOURCE, "w") as source_file:
245-
source_file.write("".join(new_content))
240+
Path(DUCKDB_PYTHON_SOURCE).write_text("".join(new_content))
246241

247242
item_list = "\n".join([f"\t{name}," for name in all_names])
248243
str_item_list = "\n".join([f"\t'{name}'," for name in all_names])
@@ -251,8 +246,7 @@ def create_definition(name, method, lambda_def) -> str:
251246

252247
init_py_content = py_start + imports + py_end
253248
# Write out the modified DUCKDB_INIT_FILE file
254-
with open(DUCKDB_INIT_FILE, "w") as source_file:
255-
source_file.write("".join(init_py_content))
249+
Path(DUCKDB_INIT_FILE).write_text("".join(init_py_content))
256250

257251

258252
if __name__ == "__main__":

scripts/generate_connection_wrapper_stubs.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@
1414

1515
def generate():
1616
# Read the DUCKDB_STUBS_FILE file
17-
with open(DUCKDB_STUBS_FILE) as source_file:
18-
source_code = source_file.readlines()
17+
source_code = Path(DUCKDB_STUBS_FILE).read_text().splitlines()
1918

2019
start_index = -1
2120
end_index = -1
@@ -41,12 +40,9 @@ def generate():
4140

4241
methods = []
4342

44-
# Read the JSON file
45-
with open(JSON_PATH) as json_file:
46-
connection_methods = json.load(json_file)
47-
48-
with open(WRAPPER_JSON_PATH) as json_file:
49-
wrapper_methods = json.load(json_file)
43+
# Read the JSON files
44+
connection_methods = json.loads(Path(JSON_PATH).read_text())
45+
wrapper_methods = json.loads(Path(WRAPPER_JSON_PATH).read_text())
5046

5147
methods.extend(connection_methods)
5248
methods.extend(wrapper_methods)
@@ -119,8 +115,7 @@ def create_overloaded_definition(name, method) -> str:
119115
new_content = start_section + with_newlines + end_section
120116

121117
# Write out the modified DUCKDB_STUBS_FILE file
122-
with open(DUCKDB_STUBS_FILE, "w") as source_file:
123-
source_file.write("".join(new_content))
118+
Path(DUCKDB_STUBS_FILE).write_text("".join(new_content))
124119

125120

126121
if __name__ == "__main__":

scripts/generate_import_cache_cpp.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77
json_data = {}
88
json_cache_path = Path(script_dir) / "cache_data.json"
99
try:
10-
with open(json_cache_path) as file:
11-
json_data = json.load(file)
10+
json_data = json.loads(Path(json_cache_path).read_text())
1211
except FileNotFoundError:
1312
print("Please first use 'generate_import_cache_json.py' first to generate json")
1413

@@ -183,8 +182,7 @@ def to_string(self):
183182
content = file.to_string()
184183
path = f"src/duckdb_py/include/duckdb_python/import_cache/modules/{file.file_name}"
185184
import_cache_path = Path(script_dir) / ".." / path
186-
with open(import_cache_path, "w") as f:
187-
f.write(content)
185+
import_cache_path.write_text(content)
188186

189187

190188
def get_root_modules(files: list[ModuleFile]):
@@ -237,8 +235,7 @@ def get_root_modules(files: list[ModuleFile]):
237235
"""
238236

239237
import_cache_path = Path(script_dir) / ".." / "src/duckdb_py/include/duckdb_python/import_cache/python_import_cache.hpp"
240-
with open(import_cache_path, "w") as f:
241-
f.write(import_cache_file)
238+
import_cache_path.write_text(import_cache_file)
242239

243240

244241
def get_module_file_path_includes(files: list[ModuleFile]):
@@ -253,8 +250,7 @@ def get_module_file_path_includes(files: list[ModuleFile]):
253250
modules_header = (
254251
Path(script_dir) / ".." / ("src/duckdb_py/include/duckdb_python/import_cache/python_import_cache_modules.hpp")
255252
)
256-
with open(modules_header, "w") as f:
257-
f.write(module_includes)
253+
modules_header.write_text(module_includes)
258254

259255
# Generate the python_import_cache_modules.hpp file
260256
# listing all the generated header files

scripts/generate_import_cache_json.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33
from typing import Union
44

55
script_dir = Path(__file__).parent
6-
7-
lines: list[str] = [file for file in open(f"{script_dir}/imports.py").read().split("\n") if file != ""]
6+
lines = [line for line in (script_dir / "imports.py").read_text().splitlines() if line]
87

98

109
class ImportCacheAttribute:
@@ -157,8 +156,7 @@ def to_json(self):
157156
existing_json_data = {}
158157
json_cache_path = Path(script_dir) / "cache_data.json"
159158
try:
160-
with open(json_cache_path) as file:
161-
existing_json_data = json.load(file)
159+
existing_json_data = json.loads(json_cache_path.read_text())
162160
except FileNotFoundError:
163161
pass
164162

@@ -184,5 +182,4 @@ def update_json(existing: dict, new: dict) -> dict:
184182
json_data = update_json(existing_json_data, json_data)
185183

186184
# Save the merged JSON data back to the file
187-
with open(json_cache_path, "w") as file:
188-
json.dump(json_data, file, indent=4)
185+
json_cache_path.write_text(json.dumps(json_data, indent=4))

tests/conftest.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
import glob
21
import os
32
import shutil
43
import warnings
54
from importlib import import_module
6-
from os.path import abspath
75
from pathlib import Path
86
from typing import Any
97

@@ -210,9 +208,9 @@ def _require(extension_name, db_name="") -> duckdb.DuckDBPyConnection | None:
210208

211209
extension_paths_found = []
212210
for pattern in extension_search_patterns:
213-
extension_pattern_abs = abspath(pattern)
211+
extension_pattern_abs = Path(pattern).resolve()
214212
print(f"Searching path: {extension_pattern_abs}")
215-
for path in glob.glob(extension_pattern_abs):
213+
for path in extension_pattern_abs.glob():
216214
extension_paths_found.append(path)
217215

218216
for path in extension_paths_found:

0 commit comments

Comments
 (0)