Skip to content

Commit eaf05be

Browse files
committed
Replace os.path with pathlib
And add type hints to configparser.py
1 parent 10f285a commit eaf05be

34 files changed

+440
-382
lines changed

doc/conf.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,12 @@
1212
# serve to show the default value.
1313

1414
# If your extensions are in another directory, add it here. If the directory
15-
# is relative to the documentation root, use os.path.abspath to make it
15+
# is relative to the documentation root, use Path.absolute to make it
1616
# absolute, like shown here.
17-
# sys.path.append(os.path.abspath('some/directory'))
17+
# sys.path.append(str(Path("some/directory").absolute()))
1818

1919
import os
20+
import inspect
2021
import sys
2122
import pytensor
2223

@@ -236,11 +237,9 @@ def find_source():
236237
obj = sys.modules[info["module"]]
237238
for part in info["fullname"].split("."):
238239
obj = getattr(obj, part)
239-
import inspect
240-
import os
241240

242-
fn = inspect.getsourcefile(obj)
243-
fn = os.path.relpath(fn, start=os.path.dirname(pytensor.__file__))
241+
fn = Path(inspect.getsourcefile(obj))
242+
fn = fn.relative_to(Path(__file__).parent)
244243
source, lineno = inspect.getsourcelines(obj)
245244
return fn, lineno, lineno + len(source) - 1
246245

doc/library/d3viz/index.rst

+2-3
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,9 @@ visualize it with :py:func:`pytensor.printing.pydotprint` as follows:
7676
.. code:: python
7777
7878
from pytensor.printing import pydotprint
79-
import os
79+
from pathlib import Path
8080
81-
if not os.path.exists('examples'):
82-
os.makedirs('examples')
81+
Path("examples").mkdir(exist_ok=True)
8382
pydotprint(predict, 'examples/mlp.png')
8483
8584

doc/troubleshooting.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ PyTensor/BLAS speed test:
259259

260260
.. code-block:: bash
261261
262-
python `python -c "import os, pytensor; print(os.path.dirname(pytensor.__file__))"`/misc/check_blas.py
262+
python $(python -c "import pathlib, pytensor; print(pathlib.Path(pytensor.__file__).parent / 'misc/check_blas.py')")
263263
264264
This will print a table with different versions of BLAS/numbers of
265265
threads on multiple CPUs. It will also print some PyTensor/NumPy

environment.yml

+1-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ dependencies:
1111
- compilers
1212
- numpy>=1.17.0,<2
1313
- scipy>=0.14,<1.14.0
14-
- filelock
14+
- filelock>=3.15
1515
- etuples
1616
- logical-unification
1717
- miniKanren
@@ -27,7 +27,6 @@ dependencies:
2727
- coveralls
2828
- diff-cover
2929
- mypy
30-
- types-filelock
3130
- types-setuptools
3231
- pytest
3332
- pytest-cov

pyproject.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ dependencies = [
4949
"setuptools>=59.0.0",
5050
"scipy>=0.14,<1.14",
5151
"numpy>=1.17.0,<2",
52-
"filelock",
52+
"filelock>=3.15",
5353
"etuples",
5454
"logical-unification",
5555
"miniKanren",

pytensor/__init__.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@
2323
# Set a default logger. It is important to do this before importing some other
2424
# pytensor code, since this code may want to log some messages.
2525
import logging
26-
import os
2726
import sys
2827
from functools import singledispatch
28+
from pathlib import Path
2929
from typing import Any, NoReturn, Optional
3030

3131
from pytensor.version import version as __version__
@@ -52,10 +52,8 @@ def disable_log_handler(logger=pytensor_logger, handler=logging_default_handler)
5252

5353
# Raise a meaningful warning/error if the pytensor directory is in the Python
5454
# path.
55-
rpath = os.path.realpath(__path__[0])
56-
for p in sys.path:
57-
if os.path.realpath(p) != rpath:
58-
continue
55+
rpath = Path(__file__).parent.resolve()
56+
if any(rpath == Path(p).resolve() for p in sys.path):
5957
raise RuntimeError("You have the pytensor directory in your Python path.")
6058

6159
from pytensor.configdefaults import config

pytensor/compile/compiledir.py

+16-22
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
"""
55

66
import logging
7-
import os
87
import pickle
98
import shutil
109
from collections import Counter
@@ -33,12 +32,11 @@ def cleanup():
3332
If there is no key left for a compiled module, we delete the module.
3433
3534
"""
36-
compiledir = config.compiledir
37-
for directory in os.listdir(compiledir):
35+
for directory in config.compiledir.iterdir():
3836
try:
39-
filename = os.path.join(compiledir, directory, "key.pkl")
37+
filename = directory / "key.pkl"
4038
# print file
41-
with open(filename, "rb") as file:
39+
with filename.open("rb") as file:
4240
try:
4341
keydata = pickle.load(file)
4442

@@ -79,7 +77,7 @@ def cleanup():
7977
"the directory containing it."
8078
)
8179
if len(keydata.keys) == 0:
82-
shutil.rmtree(os.path.join(compiledir, directory))
80+
shutil.rmtree(directory)
8381

8482
except (EOFError, AttributeError):
8583
_logger.error(
@@ -117,11 +115,11 @@ def print_compiledir_content():
117115
big_key_files = []
118116
total_key_sizes = 0
119117
nb_keys = Counter()
120-
for dir in os.listdir(compiledir):
121-
filename = os.path.join(compiledir, dir, "key.pkl")
122-
if not os.path.exists(filename):
118+
for dir in config.compiledir.iterdir():
119+
filename = dir / "key.pkl"
120+
if not filename.exists():
123121
continue
124-
with open(filename, "rb") as file:
122+
with filename.open("rb") as file:
125123
try:
126124
keydata = pickle.load(file)
127125
ops = list({x for x in flatten(keydata.keys) if isinstance(x, Op)})
@@ -134,15 +132,11 @@ def print_compiledir_content():
134132
{x for x in flatten(keydata.keys) if isinstance(x, CType)}
135133
)
136134
compile_start = compile_end = float("nan")
137-
for fn in os.listdir(os.path.join(compiledir, dir)):
138-
if fn.startswith("mod.c"):
139-
compile_start = os.path.getmtime(
140-
os.path.join(compiledir, dir, fn)
141-
)
142-
elif fn.endswith(".so"):
143-
compile_end = os.path.getmtime(
144-
os.path.join(compiledir, dir, fn)
145-
)
135+
for fn in dir.iterdir():
136+
if fn.name == "mod.c":
137+
compile_start = fn.stat().st_mtime
138+
elif fn.suffix == ".so":
139+
compile_end = fn.stat().st_mtime
146140
compile_time = compile_end - compile_start
147141
if len(ops) == 1:
148142
table.append((dir, ops[0], types, compile_time))
@@ -153,7 +147,7 @@ def print_compiledir_content():
153147
(dir, ops_to_str, types_to_str, compile_time)
154148
)
155149

156-
size = os.path.getsize(filename)
150+
size = filename.stat().st_size
157151
total_key_sizes += size
158152
if size > max_key_file_size:
159153
big_key_files.append((dir, size, ops))
@@ -239,8 +233,8 @@ def basecompiledir_ls():
239233
"""
240234
subdirs = []
241235
others = []
242-
for f in os.listdir(config.base_compiledir):
243-
if os.path.isdir(os.path.join(config.base_compiledir, f)):
236+
for f in config.base_compiledir.iterdir():
237+
if f.is_dir():
244238
subdirs.append(f)
245239
else:
246240
others.append(f)

pytensor/compile/compilelock.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import os
77
import threading
88
from contextlib import contextmanager
9+
from pathlib import Path
910

1011
import filelock
1112

@@ -35,7 +36,7 @@ def force_unlock(lock_dir: os.PathLike):
3536
Path to a directory that was locked with `lock_ctx`.
3637
"""
3738

38-
fl = filelock.FileLock(os.path.join(lock_dir, ".lock"))
39+
fl = filelock.FileLock(Path(lock_dir) / ".lock")
3940
fl.release(force=True)
4041

4142
dir_key = f"{lock_dir}-{os.getpid()}"
@@ -72,7 +73,7 @@ def lock_ctx(
7273

7374
if dir_key not in local_mem._locks:
7475
local_mem._locks[dir_key] = True
75-
fl = filelock.FileLock(os.path.join(lock_dir, ".lock"))
76+
fl = filelock.FileLock(Path(lock_dir) / ".lock")
7677
fl.acquire(timeout=timeout)
7778
try:
7879
yield

pytensor/compile/profiling.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import time
1717
from collections import Counter, defaultdict
1818
from contextlib import contextmanager
19+
from pathlib import Path
1920
from typing import Any
2021

2122
import numpy as np
@@ -34,7 +35,7 @@ def extended_open(filename, mode="r"):
3435
elif filename == "<stderr>":
3536
yield sys.stderr
3637
else:
37-
with open(filename, mode=mode) as f:
38+
with Path(filename).open(mode=mode) as f:
3839
yield f
3940

4041

0 commit comments

Comments
 (0)