[Python-ideas] Suggestion: Clear screen command for the REPL

Steven D'Aprano steve at pearwood.info
Sun Sep 18 22:32:01 EDT 2016


On Sat, Sep 17, 2016 at 11:51:16AM +0100, João Matos wrote:
> Hello,
> 
> I would like to suggest adding a clear command (not function) to Python.

While technically "clear" could be a command, I think it should not be.

First off, making clear a reserved keyword, and a statement, like print 
in Python 2, raise or import, would be a major backwards compatibility 
break. It would mean dict.clear() has to be renamed, and it would break 
lots of existing code.

So making clear a keyword is not going to happen.

If could be a pseudo-built-in, like help(), quit() and exit(), added to 
built-ins by the site module. In that case, it is *technically* possible 
to have it operate without the parentheses:

class ClearType:
    def __repr__(self):
        # code to clear the screen here
        ...

clear = ClearType()

so that when you enter clear at the interactive interpreter, __repr__ is 
called and it clears the screen. But I would argue against it. Instead, 
it is better to use the same convention that executable code that has 
side-effects should be implemented as a function call.

So I suggest following the design of exit() and quit():

py> exit
Use exit() or Ctrl-D (i.e. EOF) to exit


class ClearType:
    def __repr__(self):
        return "Use clear() or Ctrl-L (i.e. FF) to clear the screen"
    def __call__(self):
        # clear screen code goes here

clear = ClearType()  # or possibly cls ?



That is, *if* we add this function at all.

Personally, I agree with you. There are many different ways of clearing 
the screen, but they depend on the specific terminal used, whether 
readline is active or not, the operating system, etc. I think that 
interactive use is important enough that we should have a standard way 
of clearing the screen. I personally often find myself just holding down 
the Enter key until I have a blank screen.

In this ticket:

http://bugs.python.org/issue27771

Raymond Hettinger mentions that it is an often-requested feature by 
learners, and I believe that IDLE has an active task for this feature:

http://bugs.python.org/issue6143

but I don't see any tasks for a clear screen command for the default 
REPL.

I'm in favour of adding a clear() *function* to the site.py module, 
similar to exit/quit/help, but not making it "magical" or a keyword that 
doesn't require brackets. But I don't know how to implement it for the 
large variety of terminals and operating systems supported by Python.

(The fallback if all else fails is easy: get the height of the terminal, 
in lines, and print that many blank lines.)


-- 
Steve


More information about the Python-ideas mailing list