You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
SyntaxWarning for an invalid index type calls a t-string a str #138372
When a t-string is used as an index, the SyntaxWarning calls it a str. The warning reports the correct type for other types of invalid expression in that context. The TypeError also reports the correct type.
>>> [][t""]
<python-input-0>:1: SyntaxWarning: list indices must be integers or slices, not str; perhaps you missed a comma?
Traceback (most recent call last):
File "<python-input-0>", line 1, in <module>
[][t""]
~~^^^^^
TypeError: list indices must be integers or slices, not string.templatelib.Template
diff --git a/Python/codegen.c b/Python/codegen.c
index 53388592330..0b8fb42376c 100644
--- a/Python/codegen.c+++ b/Python/codegen.c@@ -29,6 +29,7 @@
#include "pycore_symtable.h" // PySTEntryObject
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString
#include "pycore_ceval.h" // SPECIAL___ENTER__
+#include "pycore_template.h"
#define NEED_OPCODE_METADATA
#include "pycore_opcode_metadata.h" // _PyOpcode_opcode_metadata, _PyOpcode_num_popped/pushed
@@ -3617,10 +3618,11 @@ infer_type(expr_ty e)
return &PyGen_Type;
case Lambda_kind:
return &PyFunction_Type;
- case JoinedStr_kind:
case TemplateStr_kind:
- case FormattedValue_kind:
case Interpolation_kind:
+ return &_PyTemplate_Type;+ case JoinedStr_kind:+ case FormattedValue_kind:
return &PyUnicode_Type;
case Constant_kind:
return Py_TYPE(e->v.Constant.value);
$ ./python -c '[][t""]'<string>:1: SyntaxWarning: list indices must be integers or slices, not string.templatelib.Template; perhaps you missed a comma?
Traceback (most recent call last):
File "<string>", line 1, in<module>
[][t""]
~~^^^^^
TypeError: list indices must be integers or slices, not string.templatelib.Template
But I wonder if there's a reason it wasn't done this way in the first place?
Activity
brianschubert commentedon Sep 2, 2025
This patch would be a possible fix:
But I wonder if there's a reason it wasn't done this way in the first place?
cc @lysnikolaou
brianschubert commentedon Sep 2, 2025
Another related case:
Ideally, the
SyntaxWarningshould say that Template objects aren't subscriptable, similar to what's done for e.g. sets:gh-138372: Fix SyntaxWarning for erroneous t-string subscription (#13…
pythongh-138372: Fix SyntaxWarning for erroneous t-string subscription (
pablogsal commentedon Sep 2, 2025
Thanks a lot @brianschubert!
[3.14] gh-138372: Fix SyntaxWarning for erroneous t-string subscripti…
brianschubert commentedon Sep 2, 2025
Backport has been merged. Thanks for the report @dscorbett!
[3.14] pythongh-138372: Fix SyntaxWarning for erroneous t-string subs…
pythongh-138372: Fix SyntaxWarning for erroneous t-string subscription (