Skip to content

Commit be86730

Browse files
committed
fix pyupgrade
1 parent bf49e6a commit be86730

File tree

16 files changed

+56
-66
lines changed

16 files changed

+56
-66
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ repos:
2020
)$
2121
- id: check-merge-conflict
2222
- repo: https://github.com/astral-sh/ruff-pre-commit
23-
rev: v0.1.11
23+
rev: v0.1.13
2424
hooks:
2525
- id: ruff
2626
args: ["--fix", "--show-source"]

pyproject.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,8 @@ disable = ["C0330", "C0326"]
130130

131131

132132
[tool.ruff]
133-
select = ["C", "E", "F", "I", "W", "UP"]
134-
ignore = ["E501", "E741", "C408", "C901"]
133+
select = ["C", "E", "F", "I", "UP", "W"]
134+
ignore = ["C408", "C901", "E501", "E741", "UP031"]
135135
exclude = ["doc/", "pytensor/_version.py", "bin/pytensor_cache.py"]
136136

137137

pytensor/graph/basic.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
TYPE_CHECKING,
1818
Any,
1919
Callable,
20-
Deque,
2120
Generic,
2221
Optional,
2322
TypeVar,
@@ -1376,7 +1375,7 @@ def _compute_deps_cache(io):
13761375
)
13771376

13781377
_clients: dict[T, list[T]] = {}
1379-
sources: Deque[T] = deque()
1378+
sources: deque[T] = deque()
13801379
search_res_len: int = 0
13811380
for snode, children in search_res:
13821381
search_res_len += 1

pytensor/link/vm.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from collections import defaultdict
1414
from collections.abc import Sequence
1515
from itertools import zip_longest
16-
from typing import TYPE_CHECKING, Any, DefaultDict, Optional
16+
from typing import TYPE_CHECKING, Any, Optional
1717

1818
from pytensor.configdefaults import config
1919
from pytensor.graph.basic import Apply, Constant, Variable
@@ -977,7 +977,7 @@ def reduce_storage_allocations(
977977
978978
"""
979979
# Collect Reallocation Info
980-
compute_map_re: DefaultDict[Variable, list[bool]] = defaultdict(lambda: [False])
980+
compute_map_re: defaultdict[Variable, list[bool]] = defaultdict(lambda: [False])
981981
for var in self.fgraph.inputs:
982982
compute_map_re[var][0] = True
983983

pytensor/tensor/blas.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1811,9 +1811,7 @@ def contiguous(var, ndim):
18111811
return " && ".join(
18121812
[
18131813
" && ".join(
1814-
"{strides}[{i}] > 0 && {strides}[{i}] % type_size == 0".format(
1815-
strides=strides, i=i
1816-
)
1814+
f"{strides}[{i}] > 0 && {strides}[{i}] % type_size == 0"
18171815
for i in range(1, ndim)
18181816
),
18191817
"(%s)"

pytensor/tensor/conv/abstract_conv.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -639,8 +639,8 @@ def border_mode_to_pad(mode, convdim, kshp):
639639
border += ((m[0], m[1]),)
640640
else:
641641
raise ValueError(
642-
"invalid border mode {}. The tuple can only contain "
643-
"integers or tuples of length 2".format(mode)
642+
f"invalid border mode {mode}. The tuple can only contain "
643+
"integers or tuples of length 2"
644644
)
645645
pad = border
646646
elif mode == "full":
@@ -651,9 +651,9 @@ def border_mode_to_pad(mode, convdim, kshp):
651651
pad = ((0, 0),) * convdim
652652
else:
653653
raise ValueError(
654-
"invalid border_mode {}, which must be either "
654+
f"invalid border_mode {mode}, which must be either "
655655
'"valid", "full", "half", an integer or a tuple '
656-
"of length {}".format(mode, convdim)
656+
f"of length {convdim}"
657657
)
658658
return pad
659659

@@ -2153,15 +2153,15 @@ def __init__(
21532153
if isinstance(border_mode, int):
21542154
if border_mode < 0:
21552155
raise ValueError(
2156-
"invalid border_mode {}, which must be a "
2157-
"non-negative integer".format(border_mode)
2156+
f"invalid border_mode {border_mode}, which must be a "
2157+
"non-negative integer"
21582158
)
21592159
border_mode = (border_mode,) * convdim
21602160
elif isinstance(border_mode, tuple):
21612161
if len(border_mode) != convdim:
21622162
raise ValueError(
2163-
"invalid border_mode {}, which must be a "
2164-
"tuple of length {}".format(border_mode, convdim)
2163+
f"invalid border_mode {border_mode}, which must be a "
2164+
f"tuple of length {convdim}"
21652165
)
21662166
new_border_mode = ()
21672167
for mode in border_mode:
@@ -2189,9 +2189,9 @@ def __init__(
21892189
border_mode = new_border_mode
21902190
elif border_mode not in ("valid", "full", "half"):
21912191
raise ValueError(
2192-
"invalid border_mode {}, which must be either "
2192+
f"invalid border_mode {border_mode}, which must be either "
21932193
'"valid", "full", "half", an integer or a tuple '
2194-
"of length {}".format(border_mode, convdim)
2194+
f"of length {convdim}"
21952195
)
21962196
if isinstance(border_mode, tuple) and all(
21972197
mode == (0, 0) or mode == 0 for mode in border_mode
@@ -2284,9 +2284,7 @@ def conv(
22842284
"""
22852285
if mode not in ("valid", "full"):
22862286
raise ValueError(
2287-
"invalid mode {}, which must be either " '"valid" or "full"'.format(
2288-
mode
2289-
)
2287+
f"invalid mode {mode}, which must be either " '"valid" or "full"'
22902288
)
22912289
if isinstance(dilation, int):
22922290
dilation = (dilation,) * self.convdim

pytensor/tensor/random/var.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,7 @@ def __str__(self):
1313

1414
class RandomGeneratorSharedVariable(SharedVariable):
1515
def __str__(self):
16-
return self.name or "RandomGeneratorSharedVariable({})".format(
17-
repr(self.container)
18-
)
16+
return self.name or f"RandomGeneratorSharedVariable({repr(self.container)})"
1917

2018

2119
@shared_constructor.register(np.random.RandomState)

pytensor/tensor/rewriting/elemwise.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import sys
22
from collections import defaultdict, deque
33
from collections.abc import Generator
4-
from functools import lru_cache
5-
from typing import DefaultDict, TypeVar
4+
from functools import cache
5+
from typing import TypeVar
66
from warnings import warn
77

88
import pytensor
@@ -686,13 +686,13 @@ def find_next_fuseable_subgraph(
686686
Elemwise Composite before being accessed again in the next iteration.
687687
"""
688688

689-
FUSEABLE_MAPPING = DefaultDict[Variable, list[Apply]]
690-
UNFUSEABLE_MAPPING = DefaultDict[Variable, set[ApplyOrOutput]]
689+
FUSEABLE_MAPPING = defaultdict[Variable, list[Apply]]
690+
UNFUSEABLE_MAPPING = defaultdict[Variable, set[ApplyOrOutput]]
691691

692692
def initialize_fuseable_mappings(
693693
*, fg: FunctionGraph
694694
) -> tuple[FUSEABLE_MAPPING, UNFUSEABLE_MAPPING]:
695-
@lru_cache(maxsize=None)
695+
@cache
696696
def elemwise_scalar_op_has_c_code(node: Apply) -> bool:
697697
# TODO: This should not play a role in non-c backends!
698698
if node.op.scalar_op.supports_c_code(node.inputs, node.outputs):
@@ -754,9 +754,9 @@ def find_fuseable_subgraph(
754754
VT = TypeVar("VT", list, set)
755755

756756
def shallow_clone_defaultdict(
757-
d: DefaultDict[KT, VT],
758-
) -> DefaultDict[KT, VT]:
759-
new_dict: DefaultDict[KT, VT] = defaultdict(d.default_factory)
757+
d: defaultdict[KT, VT],
758+
) -> defaultdict[KT, VT]:
759+
new_dict: defaultdict[KT, VT] = defaultdict(d.default_factory)
760760
new_dict.update({k: v.copy() for k, v in d.items()})
761761
return new_dict
762762

pytensor/tensor/shape.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -917,7 +917,7 @@ def shape_padaxis(t, axis):
917917

918918
ndim = _t.ndim + 1
919919
if not -ndim <= axis < ndim:
920-
msg = "axis {0} is out of bounds [-{1}, {1})".format(axis, ndim)
920+
msg = f"axis {axis} is out of bounds [-{ndim}, {ndim})"
921921
raise IndexError(msg)
922922
if axis < 0:
923923
axis += ndim

pytensor/tensor/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -167,10 +167,10 @@ def broadcast_static_dim_lengths(
167167
# Copied verbatim from numpy.lib.function_base
168168
# https://github.com/numpy/numpy/blob/f2db090eb95b87d48a3318c9a3f9d38b67b0543c/numpy/lib/function_base.py#L1999-L2029
169169
_DIMENSION_NAME = r"\w+"
170-
_CORE_DIMENSION_LIST = "(?:{0:}(?:,{0:})*)?".format(_DIMENSION_NAME)
170+
_CORE_DIMENSION_LIST = f"(?:{_DIMENSION_NAME}(?:,{_DIMENSION_NAME})*)?"
171171
_ARGUMENT = rf"\({_CORE_DIMENSION_LIST}\)"
172-
_ARGUMENT_LIST = "{0:}(?:,{0:})*".format(_ARGUMENT)
173-
_SIGNATURE = "^{0:}->{0:}$".format(_ARGUMENT_LIST)
172+
_ARGUMENT_LIST = f"{_ARGUMENT}(?:,{_ARGUMENT})*"
173+
_SIGNATURE = f"^{_ARGUMENT_LIST}->{_ARGUMENT_LIST}$"
174174

175175

176176
def _parse_gufunc_signature(signature):

tests/compile/test_shared.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ def f(var, val):
162162
with pytest.raises(TypeError):
163163
f(b, 8)
164164

165-
b = shared(float(7.234), strict=True)
165+
b = shared(7.234, strict=True)
166166
assert b.type == dscalar
167167
with pytest.raises(TypeError):
168168
f(b, 8)
@@ -268,7 +268,7 @@ def f(var, val):
268268
f(b, 8)
269269
assert b.get_value() == 8
270270

271-
b = shared(float(7.234), allow_downcast=True)
271+
b = shared(7.234, allow_downcast=True)
272272
assert b.type == dscalar
273273
f(b, 8)
274274
assert b.get_value() == 8

tests/link/c/test_params_type.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def c_code_cache_version(self):
4242

4343
def c_support_code_apply(self, node, name):
4444
float_type = node.inputs[0].type.dtype_specs()[1]
45-
return """
45+
return f"""
4646
/* Computes: x = a*x*x + b*x + c for x in tensor. */
4747
int quadratic_{name}(PyArrayObject* tensor, {float_type} a, {float_type} b, {float_type} c) {{
4848
NpyIter* iterator = NpyIter_New(tensor,
@@ -70,10 +70,7 @@ def c_support_code_apply(self, node, name):
7070
NpyIter_Deallocate(iterator);
7171
return 0;
7272
}}
73-
""".format(
74-
name=name,
75-
float_type=float_type,
76-
)
73+
"""
7774

7875
def c_code(self, node, name, inputs, outputs, sub):
7976
return """

tests/tensor/conv/c_conv3d_corr3d_ref.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -82,15 +82,15 @@ def __init__(
8282
if isinstance(border_mode, int):
8383
if border_mode < 0:
8484
raise ValueError(
85-
"invalid border_mode {}, which must be a "
86-
"non-negative integer".format(border_mode)
85+
f"invalid border_mode {border_mode}, which must be a "
86+
"non-negative integer"
8787
)
8888
border_mode = (border_mode, border_mode, border_mode)
8989
if isinstance(border_mode, tuple):
9090
if len(border_mode) != 3 or min(border_mode) < 0:
9191
raise ValueError(
92-
"invalid border_mode {}, which must be a tuple of "
93-
"three non-negative integers".format(border_mode)
92+
f"invalid border_mode {border_mode}, which must be a tuple of "
93+
"three non-negative integers"
9494
)
9595
pad_h, pad_w, pad_d = map(int, border_mode)
9696
border_mode = (pad_h, pad_w, pad_d)
@@ -99,9 +99,9 @@ def __init__(
9999
or border_mode in ("valid", "full", "half")
100100
):
101101
raise ValueError(
102-
"invalid border_mode {}, which must be either "
102+
f"invalid border_mode {border_mode}, which must be either "
103103
'"valid", "full", "half", an integer or a tuple of three'
104-
" integers".format(border_mode)
104+
" integers"
105105
)
106106
self.border_mode = border_mode
107107
if len(subsample) != 3:

tests/tensor/conv/c_conv_corr_ref.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -91,15 +91,15 @@ def __init__(
9191
if isinstance(border_mode, int):
9292
if border_mode < 0:
9393
raise ValueError(
94-
"invalid border_mode {}, which must be a "
95-
"non-negative integer".format(border_mode)
94+
f"invalid border_mode {border_mode}, which must be a "
95+
"non-negative integer"
9696
)
9797
border_mode = ((border_mode, border_mode),) * 2
9898
elif isinstance(border_mode, tuple):
9999
if len(border_mode) != 2:
100100
raise ValueError(
101-
"invalid border_mode {} which must be a "
102-
"tuple of length 2".format(border_mode)
101+
f"invalid border_mode {border_mode} which must be a "
102+
"tuple of length 2"
103103
)
104104
border = ()
105105
for mode in border_mode:
@@ -115,9 +115,9 @@ def __init__(
115115
border_mode = border
116116
elif border_mode not in ("valid", "full", "half"):
117117
raise ValueError(
118-
"invalid border_mode {}, which must be either "
118+
f"invalid border_mode {border_mode}, which must be either "
119119
'"valid", "full", "half", an integer or a tuple '
120-
"of two integers or a pair of integers".format(border_mode)
120+
"of two integers or a pair of integers"
121121
)
122122
self.border_mode = border_mode
123123
if len(subsample) != 2:

tests/tensor/test_basic.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3247,10 +3247,10 @@ def test_autocast_custom():
32473247
assert (fvector() + 1.0).dtype == "float32"
32483248
assert (dvector() + np.float32(1.1)).dtype == "float64"
32493249
assert (dvector() + np.float64(1.1)).dtype == "float64"
3250-
assert (dvector() + float(1.1)).dtype == "float64"
3250+
assert (dvector() + 1.1).dtype == "float64"
32513251
assert (fvector() + np.float32(1.1)).dtype == "float32"
32523252
assert (fvector() + np.float64(1.1)).dtype == "float64"
3253-
assert (fvector() + float(1.1)).dtype == config.floatX
3253+
assert (fvector() + 1.1).dtype == config.floatX
32543254
assert (lvector() + np.int64(1)).dtype == "int64"
32553255
assert (lvector() + np.int32(1)).dtype == "int64"
32563256
assert (lvector() + np.int16(1)).dtype == "int64"

versioneer.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,7 @@
316316
import subprocess
317317
import sys
318318
from pathlib import Path
319-
from typing import Callable, Dict
319+
from typing import Callable
320320
import functools
321321

322322
have_tomllib = True
@@ -415,8 +415,8 @@ class NotThisMethod(Exception):
415415

416416

417417
# these dictionaries contain VCS-specific tools
418-
LONG_VERSION_PY: Dict[str, str] = {}
419-
HANDLERS: Dict[str, Dict[str, Callable]] = {}
418+
LONG_VERSION_PY: dict[str, str] = {}
419+
HANDLERS: dict[str, dict[str, Callable]] = {}
420420

421421

422422
def register_vcs_handler(vcs, method): # decorator
@@ -1141,7 +1141,7 @@ def git_get_keywords(versionfile_abs):
11411141
# _version.py.
11421142
keywords = {}
11431143
try:
1144-
with open(versionfile_abs, "r") as fobj:
1144+
with open(versionfile_abs) as fobj:
11451145
for line in fobj:
11461146
if line.strip().startswith("git_refnames ="):
11471147
mo = re.search(r'=\s*"(.*)"', line)
@@ -1380,7 +1380,7 @@ def do_vcs_install(versionfile_source, ipy):
13801380
files.append(versioneer_file)
13811381
present = False
13821382
try:
1383-
with open(".gitattributes", "r") as fobj:
1383+
with open(".gitattributes") as fobj:
13841384
for line in fobj:
13851385
if line.strip().startswith(versionfile_source):
13861386
if "export-subst" in line.strip().split()[1:]:
@@ -2128,7 +2128,7 @@ def do_setup():
21282128
"__init__.py")
21292129
if os.path.exists(ipy):
21302130
try:
2131-
with open(ipy, "r") as f:
2131+
with open(ipy) as f:
21322132
old = f.read()
21332133
except OSError:
21342134
old = ""
@@ -2160,7 +2160,7 @@ def scan_setup_py():
21602160
found = set()
21612161
setters = False
21622162
errors = 0
2163-
with open("setup.py", "r") as f:
2163+
with open("setup.py") as f:
21642164
for line in f.readlines():
21652165
if "import versioneer" in line:
21662166
found.add("import")

0 commit comments

Comments
 (0)