Skip to content

Commit ce78496

Browse files
committed
Address feedback; fix template_values_get and conversion
1 parent aa7c603 commit ce78496

File tree

3 files changed

+19
-16
lines changed

3 files changed

+19
-16
lines changed

Lib/test/test_string/test_templatelib.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,19 @@ def test_creation_interleaving(self):
6767
)
6868
self.assertEqual(fstring(t), 'MariaPython')
6969

70+
def test_template_values(self):
71+
t = t'Hello, world'
72+
self.assertEqual(t.values, ())
73+
74+
name = "Lys"
75+
t = t'Hello, {name}'
76+
self.assertEqual(t.values, ("Lys",))
77+
78+
country = "GR"
79+
age = 0
80+
t = t'Hello, {name}, {age} from {country}'
81+
self.assertEqual(t.values, ("Lys", 0, "GR"))
82+
7083
def test_pickle_template(self):
7184
user = 'test'
7285
for template in (

Objects/interpolationobject.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ _PyInterpolation_Build(PyObject *value, PyObject *str, int conversion, PyObject
195195
interpolation->value = Py_NewRef(value);
196196
interpolation->expression = Py_NewRef(str);
197197
interpolation->format_spec = Py_NewRef(format_spec);
198+
interpolation->conversion = NULL;
198199

199200
if (conversion == 0) {
200201
interpolation->conversion = Py_None;

Objects/templateobject.c

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -388,29 +388,18 @@ static PyObject *
388388
template_values_get(PyObject *op, void *Py_UNUSED(data))
389389
{
390390
templateobject *self = templateobject_CAST(op);
391+
392+
Py_ssize_t len = PyTuple_GET_SIZE(self->interpolations);
391393
PyObject *values = PyTuple_New(PyTuple_GET_SIZE(self->interpolations));
392394
if (values == NULL) {
393395
return NULL;
394396
}
395397

396-
PyObject *interpolationsiter = PyObject_GetIter(self->interpolations);
397-
if (interpolationsiter == NULL) {
398-
Py_DECREF(values);
399-
return NULL;
400-
}
401-
402-
PyObject *item;
403-
Py_ssize_t index = 0;
404-
while ((item = PyIter_Next(interpolationsiter))) {
405-
PyTuple_SET_ITEM(values, index++, _PyInterpolation_GetValueRef(item));
406-
Py_DECREF(item);
398+
for (Py_ssize_t i = 0; i < len; i++) {
399+
PyObject *item = PyTuple_GET_ITEM(self->interpolations, i);
400+
PyTuple_SET_ITEM(values, i, _PyInterpolation_GetValueRef(item));
407401
}
408402

409-
Py_DECREF(interpolationsiter);
410-
if (PyErr_Occurred()) {
411-
Py_DECREF(values);
412-
return NULL;
413-
}
414403
return values;
415404
}
416405

0 commit comments

Comments
 (0)