Redirecting stdout failure with help function inside `__repr__`

Open
#101,624 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
tooling

Research direction

Start by reproducing the example with contextlib.redirect_stdout, StringIO, help(), nested repr, and instance doc assignments on the reported CPython versions. Trace how help() formats the object and writes output during the first and second calls. Done means the reproduction no longer leaks help output or raises IndexError under the redirected stdout.

Written by the indexing model from the issue text.

Description

interpreter-core type-bug

Bug report

Despite modifying sys.stdout, the help function appears to ignore it sometimes during nested usage within __repr__ and with instance __doc__ attributes.

Example:

from contextlib import redirect_stdout
from io import StringIO


class ReprDoc:
    """Class doc-string."""

    def __init__(self, value):
        self.__doc__ = value.__doc__
        self.value = value

    def __repr__(self):
        print("<===Starting Stdout Redirect===>")
        with redirect_stdout(StringIO()) as doc:
            help(self.value)
        print("<===Stopping Stdout Redirect===>")
        return doc.getvalue().splitlines()[2]


def foo():
    """Foo doc-string."""

help(ReprDoc(foo))
help(ReprDoc(foo))

Output:

<===Starting Stdout Redirect===>
<===Stopping Stdout Redirect===>
Help on ReprDoc in module __main__:

foo()
    Foo doc-string.

<===Starting Stdout Redirect===>
Help on function foo in module __main__:

foo()
    Foo doc-string.
<===Stopping Stdout Redirect===>
Traceback (most recent call last):
  ...
IndexError: list index out of range

Checking sys.stdout affirms it is correct at every step, and using print with the redirected stdout affirms that the problem comes from help itself.

I imagine this problem is related to the use of self.__doc__ assignments, though the behavior is very strange because it works the first time and then fails the second time.

Your environment

  • CPython versions tested on: >= 3.8
  • Operating system and architecture: Windows 11
Dominant language
Python
Stars
77.2k
Forks
36k
Avg merge
1d 9h
Merged PRs (30d)
558

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/cpython

All issues in python/cpython

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.