[issue36521] Consider removing docstrings from co_consts in code objects

Inada Naoki report at bugs.python.org
Wed Sep 29 07:05:04 EDT 2021


Inada Naoki <songofacandy at gmail.com> added the comment:

> There is a clear disadvantage in moving the docstring from the function's code object to the enclosing code object:
>
> Docstrings are rarely looked at (relative to other operations on functions). Inner functions and comprehensions are created many times for the same code object, and their docstring are (almost) never inspected.
>
> Given that, the obvious enhancement is to create docstrings lazily to reduce the overhead of creating a function.

Docstrings are created during unmarshaling, not when creating function. And since comprehensions don't have docstring, GH-28138 has zero cost for comprehensions.

Summary of disadvantages of each approaches:

a) status quo (e.g. co_consts[0])

* We can not share co_consts tuples between functions using same constant but having different docstring.
* Even when a function don't use docstring, it need to have co_consts[0]=None.

b) CO_DOCSTRING + co_consts[0] (ref: https://github.com/iritkatriel/cpython/pull/30 )

* Additional flag for code object
* We can not share co_consts tuples between functions using same constant but having different docstring.

c) co_doc

* Increases size of all code object, including non-functions (e.g. comprehensions, classes, modules)
  * One pointer per code object is cheap enough.
* Need additional `r_object()` call during unmarshal.
  * Need to measure this overhead.

d) MAKE_FUNCTION (GH-28138)

* Additional flag for MAKE_FUNCTION
* Push docstring to stack (e.g. one LOAD_CONST) only when the function has docstring.
  * LOAD_CONST is much cheaper than MAKE_FUNCTION
  * It is cheaper than annotations too.

---

I think (d) is the best and (c) is the second best.
Since no one support (d) for now, I will create a pull request for (c).

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue36521>
_______________________________________


More information about the Python-bugs-list mailing list