Custom commands in python IDLE

Custom commands in python IDLE

In this blog post we will discuss on how you can add your own commands to your python IDLE / REPL.

For example we will discuss on how you can exit a python REPL just by typing exit without the brackets. And implementing a clear() command which will clear the outputs from the IDLE.

Let's get started.

Step 1:

Create a .pythonrc.py file and store it a in a folder safely. Now if you use Linux based OS open your .bashrc file and add the following line.

export PYTHONSTARTUP=path-to-your-pythonrc.py

## example
export PYTHONSTARTUP=~/.pythonrc.py

If you use windows go to your Environment Variable setting and add the key PYTHONSTARTUP with the value being the path to the pythonrc.py file.

This file will be executed every time you open up a python REPL.

Step 2 (Let's write some code):

exit

If you simple type exit in you python REPL, you will get an output similar to this.

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

"Use exit() or Ctrl-D (i.e. EOF) to exit", this output is generated by the __repr__ method of the exit class so inorder to exit the REPL just by typing exit we can add the following code in the .pythonrc.py file.

# .pythonrc.py

type(exit).__repr__ = lambda self: self()

Here we are asking python to replace / map the __repr__ of exit class to a function that call the class itself. In a way mimicking exit() when you type exit

Now if you type exit without bracket the python REPL will exit out.

clear()

In order to implement the clear() method in your python REPL we can add the following code to the .pythonrc.py file.

# .pythonrc.py
def clear():
    import os
    os.system("clear")

Make sure that the import is inside the function. if not it will cause import side effects.

The full .pythonrc.py file.

type(exit).__repr__ = lambda self: self()


def clear():
    import os
    os.system("clear")

Conclusion

You can write any function that you wan to access while using your python REPL in the .pythonrc.py file. But remember that you will not be able to access these functions while running a python file. It only works in interactive mode.

Thank you for reading. Follow for more python tips and tricks.