[Tutor] Clear Screen

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 27 Jul 2001 20:23:39 -0700 (PDT)


On Fri, 27 Jul 2001, Allan Crooks wrote:

> > I was hoping there would be some way to change >>>cls() to simply >>>cls -
> > but this is close enough! :)
> 
> It just occured to me how you could do this.
> 
> class clear:
>     
>     def __repr__(self):
>         import os, sys
>         cls = os.popen("clear").read()
>         sys.stdout.write(cls)
>         return ""
> 
> cls = clear()
> 
> Now you can type cls, and it'll run the clear.__repr__ method, which
> will in turn clear the screen for you. :)


Very cool!  They also use the same technique in pydoc --- take a look at
the way they implemented repr() in pydoc.help():


###
## Inside the pydoc.Helper class...
    def __repr__(self):
        if inspect.stack()[1][3] == '?':
            self()
            return ''
        return '<pydoc.Helper instance>'
###


They're using a little bit of 'inspect'ion trickery to make __repr__
bootstrap into the help browser if we do

    pydoc.help

at the interactive prompt, and otherwise return a "normal" representation
string:


###
>>> import pydoc
>>> pydoc.help
 
Welcome to Python 2.1!  This is the online help utility.
 
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://www.python.org/doc/tut/.

[omitted text]
To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
 
help> quit
 
You're now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
 
>>> def testHelpRepr():
...     return repr(pydoc.help)
...
>>> testHelpRepr()
'<pydoc.Helper instance>'
###