0

When we use the help() function it just displays the text and I can't store it in a variable...

h = help ( 'eval' ) # Doesn't work

So what do I do? And if I need to use PyDoc, how do I do it?

2 Answers 2

2

The simple way it to use the __doc__ attribute as @Thomas said

If you want the exact output as what help(something) gives, then use

import contextlib
import io

out_io = io.StringIO()

with contextlib.redirect_stdout(out_io):
    help(eval)

out_io.seek(0)
# out has what you're looking for
out = out_io.read()

Explanation:

contextlib.redirect_stdout temporarily patches sys.stdout to any file like object you pass it

We pass in a StringIO object as the file-like object and it gets the printed value written to it

Then finally the StringIO object is seeked back to the start and read from

Sign up to request clarification or add additional context in comments.

Comments

2

The __doc__ attribute is what you're looking for:

>>> h = eval.__doc__
>>> h
'Evaluate the given source in the context of globals and locals.\n\nThe source may be a string representing a Python expression\nor a code object as returned by compile().\nThe globals must be a dictionary and locals can be any mapping,\ndefaulting to the current globals and locals.\nIf only globals is given, locals defaults to it.'

1 Comment

The output is not the same as what help('eval') gives.

Your Answer

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