cpython/Objects/interpolationobject.c
Stephen Rosen 50fe49c879
gh-150319: Replace all documentation which says "See PEP 585" (#150325)
* Replace all documentation which says "See PEP 585"

The following classes in the stdlib get simple updates:

- array.array
- asyncio.Future
- asyncio.Task
- collections.defaultdict
- collections.deque
- contextvars.ContextVar
- contextvars.Token
- ctypes.Array
- os.DirEntry
- re.Match
- re.Pattern
- string.templatelib.Interpolation
- string.templatelib.Template
- types.MappingProxyType
- queue.SimpleQueue
- weakref.ref

The following classes are documented publicly as functions, and are
therefore updated internally (`__class_getitem__.__doc__`) but not in the
public docs:

- functools.partial
- itertools.chain

The following builtin types have updates to `__class_getitem__.__doc__`
but not to any documentation pages:

- BaseExceptionGroup
- coroutines (from generators)
- dict
- enumerate
- frozendict
- frozenset
- generators (and async generators)
- list
- memoryview
- set
- slice
- tuple

Special cases:

- union objects are now documented as "supporting class-level []",
  rather than anything to do with generics.

- Templates might be generic over a single type (union, in theory) or
  over a TypeVarTuple. As this is not currently fully settled, it is
  marked with a comment and a mild hint that it is a single type is used
  (namely, "type" is singular rather than "types", plural)

* Apply suggestions from code review

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>

* Correct several class getitem docs

And expand the text for tuples.

Co-authored-by: Jelle Zijlstra <906600+JelleZijlstra@users.noreply.github.com>

* Add notes on generic typing of builtins

* Fix typo in tuple.__class_getitem__ docstring

* Typo fix: malformed refs

Fix `generic` links which weren't marked as `:ref:`.

* Strike unnecessary docs on generic-ness

Co-authored-by: Jelle Zijlstra <906600+JelleZijlstra@users.noreply.github.com>

* Apply suggestions from code review

These are applied at both the originally indicated locations and in the
corresponding docstring definitions.

Co-authored-by: Alex Waygood <66076021+AlexWaygood@users.noreply.github.com>

* Update Doc/library/re.rst

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>

* Update Objects/enumobject.c

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>

* Remove tuple generic doc in 'stdtypes' page

This is covered in more detail in the cross-linked typing documentation.
The other copy of this documentation -- in the docstring for
`tuple.__class_getitem__` -- is left in place.

* Fix whitespace around new doc of generics

Per review, do not introduce or remove whitespace such that section
breaks are altered by the introduction of doc on various generic types.

In most cases, this is a removal of an extra line.

In one case (Arrays), it is the reintroduction of a line.

Additionally, two other minor fixes are included:
- incorrect indent on 'defaultdicts'
- make `mappingproxy.__class_getitem__.__doc__` consistent with other
  mapping type generic docs

Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>

* Move placement of memoryview generic note

Previous placement was at the end of the main docstring, which is
consistent with other types but places it after a section on various
methods (which makes it read somewhat inconsistently). Moving it up
helps resolve.

Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>

* Ensure sphinxdoc does not start sentences lowercase

Lowercase class names at the start of sentences are marked out with the
`class` role. In the case of `deque`, documentation already refers to
these as `Deques`, so this form is preferred.

* Apply suggestions from code review

Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>

* Fix line endings and wrap more tightly

Line endings fixed by pre-commit ; also re-wrapped the MappingProxyType
text which was too long.

* Use 'ContextVars' style in sphinx doc

---------

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Jelle Zijlstra <906600+JelleZijlstra@users.noreply.github.com>
Co-authored-by: Alex Waygood <66076021+AlexWaygood@users.noreply.github.com>
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
2026-06-02 21:13:34 +01:00

231 lines
7 KiB
C

/* t-string Interpolation object implementation */
#include "Python.h"
#include "pycore_initconfig.h" // _PyStatus_OK
#include "pycore_interpolation.h"
#include "pycore_typeobject.h" // _PyType_GetDict
static int
_conversion_converter(PyObject *arg, PyObject **conversion)
{
if (arg == Py_None) {
return 1;
}
if (!PyUnicode_Check(arg)) {
PyErr_Format(PyExc_TypeError,
"Interpolation() argument 'conversion' must be str, not %T",
arg);
return 0;
}
Py_ssize_t len;
const char *conv_str = PyUnicode_AsUTF8AndSize(arg, &len);
if (len != 1 || !(conv_str[0] == 'a' || conv_str[0] == 'r' || conv_str[0] == 's')) {
PyErr_SetString(PyExc_ValueError,
"Interpolation() argument 'conversion' must be one of 's', 'a' or 'r'");
return 0;
}
*conversion = arg;
return 1;
}
#include "clinic/interpolationobject.c.h"
/*[clinic input]
class Interpolation "interpolationobject *" "&_PyInterpolation_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=161c64a16f9c4544]*/
typedef struct {
PyObject_HEAD
PyObject *value;
PyObject *expression;
PyObject *conversion;
PyObject *format_spec;
} interpolationobject;
#define interpolationobject_CAST(op) \
(assert(_PyInterpolation_CheckExact(op)), _Py_CAST(interpolationobject*, (op)))
/*[clinic input]
@classmethod
Interpolation.__new__ as interpolation_new
value: object
expression: object(subclass_of='&PyUnicode_Type', c_default='&_Py_STR(empty)') = ""
conversion: object(converter='_conversion_converter') = None
format_spec: object(subclass_of='&PyUnicode_Type', c_default='&_Py_STR(empty)') = ""
[clinic start generated code]*/
static PyObject *
interpolation_new_impl(PyTypeObject *type, PyObject *value,
PyObject *expression, PyObject *conversion,
PyObject *format_spec)
/*[clinic end generated code: output=6488e288765bc1a9 input=fc5c285c1dd23d36]*/
{
interpolationobject *self = PyObject_GC_New(interpolationobject, type);
if (!self) {
return NULL;
}
self->value = Py_NewRef(value);
self->expression = Py_NewRef(expression);
self->conversion = Py_NewRef(conversion);
self->format_spec = Py_NewRef(format_spec);
PyObject_GC_Track(self);
return (PyObject *) self;
}
static void
interpolation_dealloc(PyObject *op)
{
PyObject_GC_UnTrack(op);
Py_TYPE(op)->tp_clear(op);
Py_TYPE(op)->tp_free(op);
}
static int
interpolation_clear(PyObject *op)
{
interpolationobject *self = interpolationobject_CAST(op);
Py_CLEAR(self->value);
Py_CLEAR(self->expression);
Py_CLEAR(self->conversion);
Py_CLEAR(self->format_spec);
return 0;
}
static int
interpolation_traverse(PyObject *op, visitproc visit, void *arg)
{
interpolationobject *self = interpolationobject_CAST(op);
Py_VISIT(self->value);
Py_VISIT(self->expression);
Py_VISIT(self->conversion);
Py_VISIT(self->format_spec);
return 0;
}
static PyObject *
interpolation_repr(PyObject *op)
{
interpolationobject *self = interpolationobject_CAST(op);
return PyUnicode_FromFormat("%s(%R, %R, %R, %R)",
_PyType_Name(Py_TYPE(self)), self->value, self->expression,
self->conversion, self->format_spec);
}
static PyMemberDef interpolation_members[] = {
{"value", Py_T_OBJECT_EX, offsetof(interpolationobject, value), Py_READONLY, "Value"},
{"expression", Py_T_OBJECT_EX, offsetof(interpolationobject, expression), Py_READONLY, "Expression"},
{"conversion", Py_T_OBJECT_EX, offsetof(interpolationobject, conversion), Py_READONLY, "Conversion"},
{"format_spec", Py_T_OBJECT_EX, offsetof(interpolationobject, format_spec), Py_READONLY, "Format specifier"},
{NULL}
};
static PyObject*
interpolation_reduce(PyObject *op, PyObject *Py_UNUSED(dummy))
{
interpolationobject *self = interpolationobject_CAST(op);
return Py_BuildValue("(O(OOOO))", (PyObject *)Py_TYPE(op),
self->value, self->expression,
self->conversion, self->format_spec);
}
static PyMethodDef interpolation_methods[] = {
{"__reduce__", interpolation_reduce, METH_NOARGS,
PyDoc_STR("__reduce__() -> (cls, state)")},
{"__class_getitem__", Py_GenericAlias,
METH_O|METH_CLASS, PyDoc_STR("Interpolations are generic over the types of their values")},
{NULL, NULL},
};
PyTypeObject _PyInterpolation_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "string.templatelib.Interpolation",
.tp_doc = PyDoc_STR("Interpolation object"),
.tp_basicsize = sizeof(interpolationobject),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_new = interpolation_new,
.tp_alloc = PyType_GenericAlloc,
.tp_dealloc = interpolation_dealloc,
.tp_clear = interpolation_clear,
.tp_free = PyObject_GC_Del,
.tp_repr = interpolation_repr,
.tp_members = interpolation_members,
.tp_methods = interpolation_methods,
.tp_traverse = interpolation_traverse,
};
PyStatus
_PyInterpolation_InitTypes(PyInterpreterState *interp)
{
PyObject *tuple = Py_BuildValue("(ssss)", "value", "expression", "conversion", "format_spec");
if (!tuple) {
goto error;
}
PyObject *dict = _PyType_GetDict(&_PyInterpolation_Type);
if (!dict) {
Py_DECREF(tuple);
goto error;
}
int status = PyDict_SetItemString(dict, "__match_args__", tuple);
Py_DECREF(tuple);
if (status < 0) {
goto error;
}
return _PyStatus_OK();
error:
return _PyStatus_ERR("Can't initialize interpolation types");
}
PyObject *
_PyInterpolation_Build(PyObject *value, PyObject *str, int conversion, PyObject *format_spec)
{
interpolationobject *interpolation = PyObject_GC_New(interpolationobject, &_PyInterpolation_Type);
if (!interpolation) {
return NULL;
}
interpolation->value = Py_NewRef(value);
interpolation->expression = Py_NewRef(str);
interpolation->format_spec = Py_NewRef(format_spec);
interpolation->conversion = NULL;
if (conversion == 0) {
interpolation->conversion = Py_None;
}
else {
switch (conversion) {
case FVC_ASCII:
interpolation->conversion = _Py_LATIN1_CHR('a');
break;
case FVC_REPR:
interpolation->conversion = _Py_LATIN1_CHR('r');
break;
case FVC_STR:
interpolation->conversion = _Py_LATIN1_CHR('s');
break;
default:
PyErr_SetString(PyExc_SystemError,
"Interpolation() argument 'conversion' must be one of 's', 'a' or 'r'");
Py_DECREF(interpolation);
return NULL;
}
}
PyObject_GC_Track(interpolation);
return (PyObject *) interpolation;
}
PyObject *
_PyInterpolation_GetValueRef(PyObject *interpolation)
{
return Py_NewRef(interpolationobject_CAST(interpolation)->value);
}