1

On the question, How is file implemented? I learned how open() method is implemented, but I cannot find where the _PyIO_str_readline function used on its implemented is defined.

  1. https://docs.python.org/3/c-api/object.html
  2. https://github.com/python/cpython/search?q=_PyIO_str_readline

1 Answer 1

1

Your problem is that you think, _PyIO_str_readline is a function, but actually it is just a global variable (of type PyObject *), which is declared here:

extern PyObject *_PyIO_str_readline;

and defined here:

PyObject *_PyIO_str_readline = NULL;

to be NULL, but as name suggest could by any string-object (i.e. unicode in Python3 or bytes in Python2).

_PyIO_str_readline is a kind of a cache (often referenced as "interned string" in CPython - see PyUnicode_InternFromString), so every time PyObject_CallMethodObjArgs is called with "readline" as method-name, the corresponding object must not be constructed anew.

_PyIO_str_readline is initialized in PyInit__io to its actual value, using macro ADD_INTERNED:

/* Interned strings */
#define ADD_INTERNED(name) \
  if (!_PyIO_str_ ## name && \
      !(_PyIO_str_ ## name = PyUnicode_InternFromString(# name))) \
      goto fail;

...
ADD_INTERNED(readline)
..

i.e. _PyIO_str_readline is an unicode-object with value readline. Which readline-method is actually used, is resolved during the run time and depends on what self actually is.

2
  • Do you know where this variable is initialized with some value? Searching all source code, the variable is assigned nowhere. May 22, 2019 at 2:24
  • @user I have added more info concerning it.
    – ead
    May 22, 2019 at 4:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.