[Edu-sig] Re: [Idle-dev] Weird error when pydoc.help is added to builtin from site.py

Ka-Ping Yee ping@lfw.org
Tue, 12 Jun 2001 16:18:03 +0200 (CEST)


Patrick K. O'Brien wrote:
> Here is a problem we discovered on the python-edu list. We are trying to add
> pydoc help to the python environment by adding the following code to
> site.py:
>
> from pydoc import help
> import __builtin__
> __builtin__.help = help
> del help
> del __builtin__

Guido van Rossum wrote:
> There are some problems with doing it this way: the pydoc module is
> too big to be imported by site.py.  Ping has suggested that some kind
> of lightweight 'bootstrap' code should be included in site.py.  I am
> in favor of that, but I'm waiting for someone else to submit a
> patch...

Did you mean someone other than me?  Anyway, for reference, here is
the bootstrap code i initially proposed for site.py when pydoc was
being checked in:

    # Define the built-in object "help" to provide interactive help.
    class Helper:
        def __repr__(self):
            import inspect
            if inspect.stack()[1][3] == '?': # not called from a function
                self()
                return ''
            return '<Helper instance>'
        def __call__(self, arg=None):
            import pydoc
            pydoc.help(arg)
    __builtin__.help = Helper()


The check on

    inspect.stack()[1][3] == '?'

is a bit strange-looking, and could also be expressed as

    sys._getframe().f_code.co_name == '?'

The point of this check is to make sure that we go into interactive
mode only when "help" is typed directly at the top level.  If the
representation of "help" is otherwise obtained, for example:

    def f():
        print help
    f()

then the check on f_code.co_name prevents us from going into
interactive help.  Without this check, you would get a lot of strange
behaviour (e.g. the console would hang waiting for input whenever
anyone tries to inspect the "help" variable).


-- ?!ng

"If I have seen farther than others, it is because I was standing on a
really big heap of midgets."
    -- K. Eric Drexler