Skip to content

Documentation of PyFile_Write{Object,String} does not mention other writable targets, only files #111722

Open
@sobolevn

Description

@sobolevn

Feature or enhancement

The docs say:

.. c:function:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
.. index:: single: Py_PRINT_RAW
Write object *obj* to file object *p*. The only supported flag for *flags* is
:c:macro:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written
instead of the :func:`repr`. Return ``0`` on success or ``-1`` on failure; the
appropriate exception will be set.

cpython/Doc/c-api/file.rst

Lines 101 to 104 in ac01e22

.. c:function:: int PyFile_WriteString(const char *s, PyObject *p)
Write string *s* to file object *p*. Return ``0`` on success or ``-1`` on
failure; the appropriate exception will be set.

However, implementation is a bit different (here's the important part of PyFile_WriteObject which is used for both funcs):

writer = PyObject_GetAttr(f, &_Py_ID(write));
if (writer == NULL)
return -1;
if (flags & Py_PRINT_RAW) {
value = PyObject_Str(v);
}
else
value = PyObject_Repr(v);
if (value == NULL) {
Py_DECREF(writer);
return -1;
}
result = PyObject_CallOneArg(writer, value);

So, basically any object with one-argument write will work. In my tests I use io.StringIO https://github.com/python/cpython/pull/111709/files#diff-b636fe6ac656d3029788c6c9431c0884dba5316e815ec64c1165597cdee065f8R86 which is clearly not a file.

Other similar docs have this note:

Equivalent to ``p.readline([n])``, this function reads one line from the
object *p*. *p* may be a file object or any object with a
:meth:`~io.IOBase.readline`

So, I think here we can reference IOBase.write (but it does not exist for some reason):
Снимок экрана 2023-11-04 в 10 05 18

Metadata

Metadata

Assignees

Labels

docsDocumentation in the Doc dirtype-featureA feature request or enhancement

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions