It’s fun to play around with Python. One of its best features is the interactive shell where we can experiment all we want. Let’s say you open up a shell, declare a bunch of variables and want to operate on them. You don’t want to type the full variables names over and over again, right? Also, it’s difficult to remember the full names of all the inbuilt methods and functions as well. Since we are playing around with the same variables and inbuilt functions, it would be nice to have an autocomplete feature that can complete the variable and function names for us. Fortunately, Python provides that nifty little feature! Let’s see how we can enable it here.
Create file named “.pythonrc” in your home directory by running the following command on your terminal:
$ vim ~/.pythonrc
Add the following lines in that file:
import rlcompleter, readline readline.parse_and_bind("tab: complete")
Save and close the file. Now open your “~/.profile” file if you are on OS X (“~/.bashrc” file if you are on Ubuntu), go to the last line, and add the following line after that:
Save and close this file. We need to tell our “.profile” file that we have updated the environment variables. So let’s restart it by running the following command:
$ source ~/.profile
We are now ready to give it a spin. Open up the Python shell by typing “python” on your terminal. Let’s declare a string variable:
>>> my_variable = "Hello world" >>> my
In the second line, if you type “my” and hit “tab”, it will autocomplete it to “my_variable”. You can type “my_variable.” (notice the trailing “.”) and hit tab twice, it will display all the inbuilt methods that can be applied to a string variable.
If you import a module, you can see a list of all its methods as well:
>>> import os >>> os. Display all 234 possibilities? (y or n)
It will display a list of all the methods you can use with the “os” module.
3 thoughts on “Enabling Tab Autocomplete In Python Shell”
Great post, if you are using zsh
add the following to ~/.zshrc file