Skip to content

Commit 55b2f4f

Browse files
committed
Replace str.format with f-strings
1 parent e2f9cb8 commit 55b2f4f

39 files changed

+361
-462
lines changed

pytensor/compile/builders.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -434,7 +434,7 @@ def __hash__(self):
434434
def __str__(self):
435435
name = self.__class__.__name__ if self.name is None else self.name
436436
is_inline = self.is_inline
437-
return "{name}{{inline={is_inline}}}".format(**locals())
437+
return f"{name}{{inline={is_inline}}}"
438438

439439
def _combine_list_overrides(self, default_outs, custom_outs, callable_args):
440440
"""Combines default and custom overrides into a single list of outputs."""

pytensor/compile/function/types.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1890,11 +1890,7 @@ def get_plural(n):
18901890
)
18911891
else:
18921892
if n_unnamed_inputs == 0:
1893-
msg = "The function has {} named input{} ({}).".format(
1894-
n_named_inputs,
1895-
get_plural(n_named_inputs),
1896-
", ".join(named_inputs),
1897-
)
1893+
msg = f"The function has {n_named_inputs} named input{get_plural(n_named_inputs)} ({', '.join(named_inputs)})."
18981894
else:
18991895
msg = (
19001896
f"The function has {n_named_inputs} named input{get_plural(n_named_inputs)} ({', '.join(named_inputs)}), and {n_unnamed_inputs} unnamed "

pytensor/graph/rewriting/basic.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1664,15 +1664,12 @@ def __str__(self):
16641664

16651665
def pattern_to_str(pattern):
16661666
if isinstance(pattern, list | tuple):
1667-
return "{}({})".format(
1668-
str(pattern[0]),
1669-
", ".join(pattern_to_str(p) for p in pattern[1:]),
1670-
)
1667+
args = ", ".join(pattern_to_str(p) for p in pattern[1:])
1668+
return f"{pattern[0]!s}({args})"
16711669
elif isinstance(pattern, dict):
1672-
return "{} subject to {}".format(
1673-
pattern_to_str(pattern["pattern"]),
1674-
str(pattern.get("constraint", "no conditions")),
1675-
)
1670+
a = pattern_to_str(pattern["pattern"])
1671+
b = pattern.get("constraint", "no conditions")
1672+
return f"{a} subject to {b}"
16761673
else:
16771674
return str(pattern)
16781675

pytensor/graph/utils.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -245,10 +245,9 @@ def __str__(self):
245245
else:
246246

247247
def __str__(self):
248-
return "{}{{{}}}".format(
249-
self.__class__.__name__,
250-
", ".join(f"{p}={getattr(self, p)!r}" for p in props),
251-
)
248+
classname = self.__class__.__name__
249+
args = ", ".join(f"{p}={getattr(self, p)!r}" for p in props)
250+
return f"{classname}{{{args}}}"
252251

253252
dct["__str__"] = __str__
254253

pytensor/link/c/basic.py

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,6 @@ def struct_gen(args, struct_builders, blocks, sub):
219219
"""
220220
struct_decl = ""
221221
struct_init_head = ""
222-
struct_init_tail = ""
223222
struct_cleanup = ""
224223

225224
for block in struct_builders:
@@ -243,15 +242,15 @@ def struct_gen(args, struct_builders, blocks, sub):
243242
# decrements the storage's refcount in the destructor
244243
storage_decref = "\n".join(f"Py_XDECREF(this->{arg});" for arg in args)
245244

246-
args_names = ", ".join(args)
247245
args_decl = ", ".join(f"PyObject* {arg}" for arg in args)
248246

249247
# The following code stores the exception data in __ERROR, which
250248
# is a special field of the struct. __ERROR is a list of length 3
251249
# that holds the type, the value and the traceback. After storing
252250
# the error, we return the failure code so we know which code
253251
# block failed.
254-
do_return = """
252+
failure_var = sub["failure_var"]
253+
do_return = f"""
255254
if ({failure_var}) {{
256255
// When there is a failure, this code puts the exception
257256
// in __ERROR.
@@ -274,15 +273,13 @@ def struct_gen(args, struct_builders, blocks, sub):
274273
}}
275274
// The failure code is returned to index what code block failed.
276275
return {failure_var};
277-
""".format(**sub)
278-
279-
sub = dict(sub)
280-
sub.update(locals())
276+
"""
281277

282278
# TODO: add some error checking to make sure storage_<x> are
283279
# 1-element lists and __ERROR is a 3-elements list.
284280

285-
struct_code = """
281+
name = sub["name"]
282+
struct_code = f"""
286283
namespace {{
287284
struct {name} {{
288285
PyObject* __ERROR;
@@ -326,7 +323,7 @@ def struct_gen(args, struct_builders, blocks, sub):
326323
}}
327324
}};
328325
}}
329-
""".format(**sub)
326+
"""
330327

331328
return struct_code
332329

@@ -370,13 +367,10 @@ def get_c_init(fgraph, r, name, sub):
370367
Wrapper around c_init that initializes py_name to Py_None.
371368
372369
"""
373-
pre = (
374-
""
375-
"""
370+
pre = f"""
376371
py_{name} = Py_None;
377372
{{Py_XINCREF(py_{name});}}
378-
""".format(**locals())
379-
)
373+
"""
380374
return pre + r.type.c_init(name, sub)
381375

382376

@@ -410,10 +404,10 @@ def get_c_extract(fgraph, r, name, sub):
410404
else:
411405
c_extract = r.type.c_extract(name, sub, False)
412406

413-
pre = """
407+
pre = f"""
414408
py_{name} = PyList_GET_ITEM(storage_{name}, 0);
415409
{{Py_XINCREF(py_{name});}}
416-
""".format(**locals())
410+
"""
417411
return pre + c_extract
418412

419413

@@ -439,10 +433,10 @@ def get_c_extract_out(fgraph, r, name, sub):
439433
else:
440434
c_extract = r.type.c_extract_out(name, sub, check_input, check_broadcast=False)
441435

442-
pre = """
436+
pre = f"""
443437
py_{name} = PyList_GET_ITEM(storage_{name}, 0);
444438
{{Py_XINCREF(py_{name});}}
445-
""".format(**locals())
439+
"""
446440
return pre + c_extract
447441

448442

@@ -451,9 +445,9 @@ def get_c_cleanup(fgraph, r, name, sub):
451445
Wrapper around c_cleanup that decrefs py_name.
452446
453447
"""
454-
post = """
448+
post = f"""
455449
{{Py_XDECREF(py_{name});}}
456-
""".format(**locals())
450+
"""
457451
return r.type.c_cleanup(name, sub) + post
458452

459453

@@ -462,15 +456,17 @@ def get_c_sync(fgraph, r, name, sub):
462456
Wrapper around c_sync that syncs py_name with storage.
463457
464458
"""
465-
return """
459+
failure_var = sub["failure_var"]
460+
sync = r.type.c_sync(name, sub)
461+
return f"""
466462
if (!{failure_var}) {{
467463
{sync}
468464
PyObject* old = PyList_GET_ITEM(storage_{name}, 0);
469465
{{Py_XINCREF(py_{name});}}
470466
PyList_SET_ITEM(storage_{name}, 0, py_{name});
471467
{{Py_XDECREF(old);}}
472468
}}
473-
""".format(**dict(sync=r.type.c_sync(name, sub), name=name, **sub))
469+
"""
474470

475471

476472
def apply_policy(fgraph, policy, r, name, sub):

pytensor/link/c/cmodule.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1966,14 +1966,14 @@ def _try_flags(
19661966
return False
19671967

19681968
code = (
1969-
"""
1969+
f"""
19701970
{preamble}
19711971
int main(int argc, char** argv)
19721972
{{
19731973
{body}
19741974
return 0;
19751975
}}
1976-
""".format(**locals())
1976+
"""
19771977
).encode()
19781978
return cls._try_compile_tmp(
19791979
code,

pytensor/link/c/interface.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -558,7 +558,9 @@ def c_extract_out(
558558
uninitialized.
559559
560560
"""
561-
return """
561+
c_init_code = self.c_init(name, sub)
562+
c_extract_code = self.c_extract(name, sub, check_input)
563+
return f"""
562564
if (py_{name} == Py_None)
563565
{{
564566
{c_init_code}
@@ -567,13 +569,7 @@ def c_extract_out(
567569
{{
568570
{c_extract_code}
569571
}}
570-
""".format(
571-
**dict(
572-
name=name,
573-
c_init_code=self.c_init(name, sub),
574-
c_extract_code=self.c_extract(name, sub, check_input),
575-
)
576-
)
572+
"""
577573

578574
def c_cleanup(self, name: str, sub: dict[str, str]) -> str:
579575
"""Return C code to clean up after :meth:`CLinkerType.c_extract`.

pytensor/link/c/op.py

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -587,24 +587,15 @@ def c_code(self, node, name, inp, out, sub):
587587
params = f", {sub['params']}"
588588

589589
# Generate the C code
590-
return """
590+
return f"""
591591
{define_macros}
592592
{{
593-
if ({func_name}({func_args}{params}) != 0) {{
594-
{fail}
593+
if ({self.func_name}({self.format_c_function_args(inp, out)}{params}) != 0) {{
594+
{sub['fail']}
595595
}}
596596
}}
597597
{undef_macros}
598-
""".format(
599-
**dict(
600-
func_name=self.func_name,
601-
fail=sub["fail"],
602-
params=params,
603-
func_args=self.format_c_function_args(inp, out),
604-
define_macros=define_macros,
605-
undef_macros=undef_macros,
606-
)
607-
)
598+
"""
608599
else:
609600
if "code" in self.code_sections:
610601
op_code = self.code_sections["code"]

pytensor/link/c/params_type.py

Lines changed: 26 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -262,9 +262,10 @@ def __init__(self, params_type, **kwargs):
262262
self.__dict__.update(__params_type__=params_type, __signatures__=None)
263263

264264
def __repr__(self):
265-
return "Params({})".format(
266-
", ".join((f"{k}:{type(self[k]).__name__}:{self[k]}") for k in sorted(self))
265+
args = ", ".join(
266+
(f"{k}:{type(self[k]).__name__}:{self[k]}") for k in sorted(self)
267267
)
268+
return f"Params({args})"
268269

269270
def __getattr__(self, key):
270271
if key not in self:
@@ -422,9 +423,10 @@ def __getattr__(self, key):
422423
return super().__getattr__(self, key)
423424

424425
def __repr__(self):
425-
return "ParamsType<{}>".format(
426-
", ".join((f"{self.fields[i]}:{self.types[i]}") for i in range(self.length))
426+
args = ", ".join(
427+
f"{self.fields[i]}:{self.types[i]}" for i in range(self.length)
427428
)
429+
return f"ParamsType<{args}>"
428430

429431
def __eq__(self, other):
430432
return (
@@ -730,25 +732,24 @@ def c_support_code(self, **kwargs):
730732
struct_init = "\n".join(c_init_list)
731733
struct_cleanup = "\n".join(c_cleanup_list)
732734
struct_extract = "\n\n".join(c_extract_list)
733-
struct_extract_method = """
735+
args = "\n".join(
736+
f"case {i}: extract_{self.fields[i]}(object); break;"
737+
for i in range(self.length)
738+
)
739+
struct_extract_method = f"""
734740
void extract(PyObject* object, int field_pos) {{
735741
switch(field_pos) {{
736742
// Extraction cases.
737-
{}
743+
{args}
738744
// Default case.
739745
default:
740746
PyErr_Format(PyExc_TypeError, "ParamsType: no extraction defined for a field %d.", field_pos);
741747
this->setErrorOccurred();
742748
break;
743749
}}
744750
}}
745-
""".format(
746-
"\n".join(
747-
("case %d: extract_%s(object); break;" % (i, self.fields[i]))
748-
for i in range(self.length)
749-
)
750-
)
751-
final_struct_code = """
751+
"""
752+
final_struct_code = f"""
752753
/** ParamsType {struct_name} **/
753754
#ifndef {struct_name_defined}
754755
#define {struct_name_defined}
@@ -790,17 +791,7 @@ def c_support_code(self, **kwargs):
790791
}};
791792
#endif
792793
/** End ParamsType {struct_name} **/
793-
""".format(
794-
**dict(
795-
struct_name_defined=struct_name_defined,
796-
struct_name=struct_name,
797-
struct_declare=struct_declare,
798-
struct_init=struct_init,
799-
struct_cleanup=struct_cleanup,
800-
struct_extract=struct_extract,
801-
struct_extract_method=struct_extract_method,
802-
)
803-
)
794+
"""
804795

805796
return [*sorted(c_support_code_set), final_struct_code]
806797

@@ -813,9 +804,9 @@ def c_code_cache_version(self):
813804
# pointers.
814805

815806
def c_declare(self, name, sub, check_input=True):
816-
return """
817-
{struct_name}* {name};
818-
""".format(**dict(struct_name=self.name, name=name))
807+
return f"""
808+
{self.name}* {name};
809+
"""
819810

820811
def c_init(self, name, sub):
821812
# NB: It seems c_init() is not called for an op param.
@@ -831,40 +822,33 @@ def c_cleanup(self, name, sub):
831822
"""
832823

833824
def c_extract(self, name, sub, check_input=True, **kwargs):
834-
return """
825+
fields_list = ", ".join(f'"{x}"' for x in self.fields)
826+
return f"""
835827
/* Seems c_init() is not called for a op param. So I call `new` here. */
836-
{name} = new {struct_name};
828+
{name} = new {self.name};
837829
838830
{{ // This need a separate namespace for Clinker
839831
const char* fields[] = {{{fields_list}}};
840832
if (py_{name} == Py_None) {{
841833
PyErr_SetString(PyExc_ValueError, "ParamsType: expected an object, not None.");
842-
{fail}
834+
{sub['fail']}
843835
}}
844-
for (int i = 0; i < {length}; ++i) {{
836+
for (int i = 0; i < {self.length}; ++i) {{
845837
PyObject* o = PyDict_GetItemString(py_{name}, fields[i]);
846838
if (o == NULL) {{
847839
PyErr_Format(PyExc_TypeError, "ParamsType: missing expected attribute \\"%s\\" in object.", fields[i]);
848-
{fail}
840+
{sub['fail']}
849841
}}
850842
{name}->extract(o, i);
851843
if ({name}->errorOccurred()) {{
852844
/* The extract code from attribute type should have already raised a Python exception,
853845
* so we just print the attribute name in stderr. */
854846
fprintf(stderr, "\\nParamsType: error when extracting value for attribute \\"%s\\".\\n", fields[i]);
855-
{fail}
847+
{sub['fail']}
856848
}}
857849
}}
858850
}}
859-
""".format(
860-
**dict(
861-
name=name,
862-
struct_name=self.name,
863-
length=self.length,
864-
fail=sub["fail"],
865-
fields_list='"{}"'.format('", "'.join(self.fields)),
866-
)
867-
)
851+
"""
868852

869853
def c_sync(self, name, sub):
870854
# FIXME: Looks like we need to decrement a reference count our two.

0 commit comments

Comments
 (0)