Skip to content

Commit 93825dc

Browse files
committed
Replace % formatting with f-strings
1 parent 55b2f4f commit 93825dc

22 files changed

+115
-133
lines changed

doc/generate_dtype_tensor_table.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
if len(shape[1]) < 6 or len(set(shape[1])) > 1:
3232
broadcastable_str = str(shape[1])
3333
else:
34-
broadcastable_str = '(%s,) * %d' % (str(shape[1][0]), len(shape[1]))
34+
broadcastable_str = f'({shape[1][0]},) * {len(shape[1])}'
3535
print('%s%-10s %-10s %-4s %-15s %-20s' %(
3636
letter[0], shape[0], letter[1], len(shape[1]), s, broadcastable_str
3737
))

pytensor/compile/monitormode.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,6 @@ def detect_nan(fgraph, i, node, fn):
110110
):
111111
print("*** NaN detected ***")
112112
debugprint(node)
113-
print("Inputs : %s" % [input[0] for input in fn.inputs])
114-
print("Outputs: %s" % [output[0] for output in fn.outputs])
113+
print(f"Inputs : {[input[0] for input in fn.inputs]}")
114+
print(f"Outputs: {[output[0] for output in fn.outputs]}")
115115
break

pytensor/compile/profiling.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -753,14 +753,11 @@ def summary_nodes(self, file=sys.stderr, N=None):
753753
)
754754
# Same as before, this I've sacrificed some information making
755755
# the output more readable
756+
percent = sum(f for f, t, a, nd_id, nb_call in atimes[N:])
757+
duration = sum(t for f, t, a, nd_id, nb_call in atimes[N:])
756758
print(
757-
" ... (remaining %i Apply instances account for "
758-
"%.2f%%(%.2fs) of the runtime)"
759-
% (
760-
max(0, len(atimes) - N),
761-
sum(f for f, t, a, nd_id, nb_call in atimes[N:]),
762-
sum(t for f, t, a, nd_id, nb_call in atimes[N:]),
763-
),
759+
f" ... (remaining {max(0, len(atimes) - N)} Apply instances account for "
760+
f"{percent:.2f}%%({duration:.2f}s) of the runtime)",
764761
file=file,
765762
)
766763
print("", file=file)

pytensor/link/c/basic.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,8 @@ def __init__(self, declare, behavior, cleanup, sub):
8787
# for that...)
8888
# we need the label even if cleanup is empty because the
8989
# behavior block jumps there on failure
90-
self.cleanup = (
91-
"__label_%(id)i:\n" % sub + cleanup + "\ndouble __DUMMY_%(id)i;\n" % sub
92-
) # % sub
90+
id = sub["id"]
91+
self.cleanup = f"__label_{id}:\n{cleanup}\ndouble __DUMMY_{id};\n"
9392

9493

9594
def failure_code(sub, use_goto=True):
@@ -114,14 +113,16 @@ def failure_code(sub, use_goto=True):
114113
goto_statement = "goto __label_%(id)i;" % sub
115114
else:
116115
goto_statement = ""
117-
return """{
118-
%(failure_var)s = %(id)i;
119-
if (!PyErr_Occurred()) {
116+
id = sub["id"]
117+
failure_var = sub["failure_var"]
118+
return f"""{{
119+
{failure_var} = {id};
120+
if (!PyErr_Occurred()) {{
120121
PyErr_SetString(PyExc_RuntimeError,
121122
"Unexpected error in an Op's C code. "
122123
"No Python exception was set.");
123-
}
124-
%(goto_statement)s}""" % dict(sub, goto_statement=goto_statement)
124+
}}
125+
{goto_statement}}}"""
125126

126127

127128
def failure_code_init(sub):
@@ -135,17 +136,15 @@ def failure_code_init(sub):
135136
* failure_var -> must contain a variable name to use for
136137
the failure code.
137138
"""
138-
return (
139-
"""{
140-
if (!PyErr_Occurred()) {
139+
id = sub["id"]
140+
return f"""{{
141+
if (!PyErr_Occurred()) {{
141142
PyErr_SetString(PyExc_RuntimeError,
142143
"Unexpected error in an Op's C code. "
143144
"No Python exception was set.");
144-
}
145-
return %(id)d;
146-
}"""
147-
% sub
148-
)
145+
}}
146+
return {id};
147+
}}"""
149148

150149

151150
def code_gen(blocks):
@@ -1657,10 +1656,9 @@ def instantiate_code(self, n_args):
16571656
file=code,
16581657
)
16591658
print(" assert(PyTuple_Check(argtuple));", file=code)
1660-
print(" if (%(n_args)i != PyTuple_Size(argtuple)){ " % locals(), file=code)
1659+
print(f" if ({n_args} != PyTuple_Size(argtuple)){{ ", file=code)
16611660
print(
1662-
' PyErr_Format(PyExc_TypeError, "Wrong number of arguments, expected %(n_args)i, got %%i", (int)PyTuple_Size(argtuple));'
1663-
% locals(),
1661+
f' PyErr_Format(PyExc_TypeError, "Wrong number of arguments, expected {n_args}, got %%i", (int)PyTuple_Size(argtuple));',
16641662
file=code,
16651663
)
16661664
print(" return NULL;", file=code)

pytensor/link/c/op.py

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -513,8 +513,6 @@ def get_c_macros(
513513
self, node: Apply, name: str, check_input: bool | None = None
514514
) -> tuple[str, str]:
515515
"Construct a pair of C ``#define`` and ``#undef`` code strings."
516-
define_template = "#define %s %s"
517-
undef_template = "#undef %s"
518516
define_macros = []
519517
undef_macros = []
520518

@@ -535,28 +533,23 @@ def get_c_macros(
535533

536534
vname = variable_names[i]
537535

538-
macro_items = (f"DTYPE_{vname}", f"npy_{v.type.dtype}")
539-
define_macros.append(define_template % macro_items)
540-
undef_macros.append(undef_template % macro_items[0])
536+
define_macros.append(f"#define DTYPE_{vname} npy_{v.type.dtype}")
537+
undef_macros.append(f"#undef DTYPE_{vname}")
541538

542539
d = np.dtype(v.type.dtype)
543540

544-
macro_items_2 = (f"TYPENUM_{vname}", d.num)
545-
define_macros.append(define_template % macro_items_2)
546-
undef_macros.append(undef_template % macro_items_2[0])
541+
define_macros.append(f"#define TYPENUM_{vname} {d.num}")
542+
undef_macros.append(f"#undef TYPENUM_{vname}")
547543

548-
macro_items_3 = (f"ITEMSIZE_{vname}", d.itemsize)
549-
define_macros.append(define_template % macro_items_3)
550-
undef_macros.append(undef_template % macro_items_3[0])
544+
define_macros.append(f"#define ITEMSIZE_{vname} {d.itemsize}")
545+
undef_macros.append(f"#undef ITEMSIZE_{vname}")
551546

552547
# Generate a macro to mark code as being apply-specific
553-
define_macros.append(define_template % ("APPLY_SPECIFIC(str)", f"str##_{name}"))
554-
undef_macros.append(undef_template % "APPLY_SPECIFIC")
548+
define_macros.append(f"#define APPLY_SPECIFIC(str) str##_{name}")
549+
undef_macros.append("#undef APPLY_SPECIFIC")
555550

556-
define_macros.extend(
557-
define_template % (n, v) for n, v in self.__get_op_params()
558-
)
559-
undef_macros.extend(undef_template % (n,) for n, _ in self.__get_op_params())
551+
define_macros.extend(f"#define {n} {v}" for n, v in self.__get_op_params())
552+
undef_macros.extend(f"#undef {n}" for n, _ in self.__get_op_params())
560553

561554
return "\n".join(define_macros), "\n".join(undef_macros)
562555

pytensor/link/c/type.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -208,29 +208,29 @@ def c_sync(self, name, sub):
208208
freefunc = self.freefunc
209209
if freefunc is None:
210210
freefunc = "NULL"
211-
s = """
212-
Py_XDECREF(py_%(name)s);
213-
if (%(name)s == NULL) {
214-
py_%(name)s = Py_None;
215-
Py_INCREF(py_%(name)s);
216-
} else {
217-
py_%(name)s = PyCapsule_New((void *)%(name)s, NULL,
211+
s = f"""
212+
Py_XDECREF(py_{name});
213+
if ({name} == NULL) {{
214+
py_{name} = Py_None;
215+
Py_INCREF(py_{name});
216+
}} else {{
217+
py_{name} = PyCapsule_New((void *){name}, NULL,
218218
_capsule_destructor);
219-
if (py_%(name)s != NULL) {
220-
if (PyCapsule_SetContext(py_%(name)s, (void *)%(freefunc)s) != 0) {
219+
if (py_{name} != NULL) {{
220+
if (PyCapsule_SetContext(py_{name}, (void *){freefunc}) != 0) {{
221221
/* This won't trigger a call to freefunc since it could not be
222222
set. The error case below will do it. */
223-
Py_DECREF(py_%(name)s);
223+
Py_DECREF(py_{name});
224224
/* Signal the error */
225-
py_%(name)s = NULL;
226-
}
227-
}
228-
}"""
225+
py_{name} = NULL;
226+
}}
227+
}}
228+
}}"""
229229
if self.freefunc is not None:
230-
s += """
231-
if (py_%(name)s == NULL) { %(freefunc)s(%(name)s); }
230+
s += f"""
231+
if (py_{name} == NULL) {{ {freefunc}({name}); }}
232232
"""
233-
return s % dict(name=name, freefunc=freefunc)
233+
return s
234234

235235
def c_cleanup(self, name, sub):
236236
# No need to do anything here since the CObject/Capsule will

pytensor/misc/check_duplicate_key.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
if DISPLAY_DUPLICATE_KEYS:
3737
for k, v in keys.items():
3838
if v > 1:
39-
print("Duplicate key (%i copies): %s" % (v, pickle.loads(k)))
39+
print(f"Duplicate key ({v} copies): {pickle.loads(k)}")
4040

4141
# nb seen -> how many keys
4242
nbs_keys = Counter(val for val in keys.values())

pytensor/printing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1120,7 +1120,7 @@ def process_graph(self, inputs, outputs, updates=None, display_inputs=False):
11201120
i += 1
11211121
if output.name is not None or output in outputs:
11221122
if output.name is None:
1123-
name = "out[%i]" % outputs.index(output)
1123+
name = f"out[{outputs.index(output)}]"
11241124
else:
11251125
name = output.name
11261126
# backport

pytensor/tensor/blas.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1827,7 +1827,7 @@ def contiguous(var, ndim):
18271827
]
18281828

18291829
z_shape_correct = " && ".join(
1830-
"PyArray_DIMS(%s)[%i] == %s" % (_z, i, dim) for i, dim in enumerate(z_dims)
1830+
f"PyArray_DIMS({_z})[{i}] == {dim}" for i, dim in enumerate(z_dims)
18311831
)
18321832
z_shape = ", ".join(z_dims)
18331833
z_contiguous = contiguous(_z, z_ndim)

pytensor/tensor/math.py

Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -223,32 +223,31 @@ def c_code(self, node, name, inp, out, sub):
223223
{fail}
224224
}}
225225
"""
226-
ret = """
226+
return f"""
227227
int axis;
228228
229-
Py_CLEAR(%(argmax)s);//todo pass them as out parameter.
230-
%(axis_code)s
231-
232-
%(argmax)s = (PyArrayObject*)PyArray_ArgMax(%(x)s, axis, NULL);
233-
if(%(argmax)s == NULL){
234-
%(fail)s;
235-
}
236-
if(!PyArray_CheckExact(%(argmax)s)){
237-
%(argmax)s = (PyArrayObject*)PyArray_FromAny((PyObject*)%(argmax)s, NULL, 0, 0, NPY_ARRAY_ENSUREARRAY, NULL);
238-
if(%(argmax)s == NULL){
239-
%(fail)s;
240-
}
241-
}
242-
if(PyArray_TYPE(%(argmax)s) != NPY_INT64){
243-
PyObject * tmp = PyArray_Cast(%(argmax)s, NPY_INT64);
244-
if (NULL == tmp){
245-
%(fail)s;
246-
}
247-
Py_DECREF(%(argmax)s);
248-
%(argmax)s = (PyArrayObject*)tmp;
249-
}
229+
Py_CLEAR({argmax});//todo pass them as out parameter.
230+
{axis_code}
231+
232+
{argmax} = (PyArrayObject*)PyArray_ArgMax({x}, axis, NULL);
233+
if({argmax} == NULL){{
234+
{fail};
235+
}}
236+
if(!PyArray_CheckExact({argmax})){{
237+
{argmax} = (PyArrayObject*)PyArray_FromAny((PyObject*){argmax}, NULL, 0, 0, NPY_ARRAY_ENSUREARRAY, NULL);
238+
if({argmax} == NULL){{
239+
{fail};
240+
}}
241+
}}
242+
if(PyArray_TYPE({argmax}) != NPY_INT64){{
243+
PyObject * tmp = PyArray_Cast({argmax}, NPY_INT64);
244+
if (NULL == tmp){{
245+
{fail};
246+
}}
247+
Py_DECREF({argmax});
248+
{argmax} = (PyArrayObject*)tmp;
249+
}}
250250
"""
251-
return ret % locals()
252251

253252
def c_code_cache_version(self):
254253
return (2,)
@@ -2602,10 +2601,7 @@ def impl(self, x, y):
26022601
def c_code(self, node, name, inp, out, sub):
26032602
x, y = inp
26042603
(z,) = out
2605-
return (
2606-
"%(z)s = ((%(x)s == 0) ? (%(y)s) : "
2607-
+ "((%(y)s == 0) ? (%(x)s) : ((%(y)s)*(%(x)s))) );"
2608-
) % locals()
2604+
return f"{z} = (({x} == 0) ? ({y}) : (({y} == 0) ? ({x}) : (({y})*({x}))) );"
26092605

26102606
def c_code_cache_version(self):
26112607
return (1,)

pytensor/tensor/rewriting/math.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3254,7 +3254,7 @@ def simplify_mul(tree):
32543254
rval = [neg, s_inputs]
32553255
else:
32563256
rval = tree
3257-
# print 'simplify_mul: %s -> %s' % (tree, rval)
3257+
# print(f"simplify_mul: {tree} -> {rval}")
32583258
return rval
32593259

32603260

pytensor/tensor/shape.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ def params_type(self):
243243
return ParamsType(i=pytensor.scalar.basic.int64)
244244

245245
def __str__(self):
246-
return "%s{%i}" % (self.__class__.__name__, self.i)
246+
return f"{self.__class__.__name__}{{{self.i}}}"
247247

248248
def make_node(self, x):
249249
if not (isinstance(x, Variable) and hasattr(x.type, "ndim")):

pytensor/tensor/subtensor.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1073,20 +1073,20 @@ def input_pos():
10731073

10741074
def init_entry(entry, depth=0):
10751075
if isinstance(entry, np.integer | int):
1076-
init_cmds.append("subtensor_spec[%i] = %i;" % (spec_pos(), entry))
1076+
init_cmds.append(f"subtensor_spec[{spec_pos()}] = {entry};")
10771077
inc_spec_pos(1)
10781078
if depth == 0:
10791079
is_slice.append(0)
10801080
elif isinstance(entry, Type):
10811081
init_cmds.append(
1082-
"subtensor_spec[%i] = %s;" % (spec_pos(), inputs[input_pos()])
1082+
f"subtensor_spec[{spec_pos()}] = {inputs[input_pos()]};"
10831083
)
10841084
inc_spec_pos(1)
10851085
inc_input_pos(1)
10861086
if depth == 0:
10871087
is_slice.append(0)
10881088
elif entry is None:
1089-
init_cmds.append("subtensor_spec[%i] = %i;" % (spec_pos(), NONE_CODE))
1089+
init_cmds.append(f"subtensor_spec[{spec_pos()}] = {NONE_CODE};")
10901090
inc_spec_pos(1)
10911091
if depth == 0:
10921092
is_slice.append(0)

tests/compile/function/test_types.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -902,8 +902,8 @@ def test_deepcopy(self):
902902
assert f._check_for_aliased_inputs is g._check_for_aliased_inputs
903903
assert f.name == g.name
904904
assert f.maker.fgraph.name == g.maker.fgraph.name
905-
# print 'f.defaults = %s' % (f.defaults, )
906-
# print 'g.defaults = %s' % (g.defaults, )
905+
# print(f"{f.defaults = }")
906+
# print(f"{g.defaults = }")
907907
for (f_req, f_feed, f_val), (g_req, g_feed, g_val) in zip(
908908
f.defaults, g.defaults
909909
):

0 commit comments

Comments
 (0)