Boris Paskhaver

The IPython shell is a powerful expansion pack to Python, the world’s most popular programming language. It accelerates developer productivity by adding a slew of features to Python’s standard execution environment, including auto-completion, command history, file writes, and more. 

One of IPython’s most celebrated features is magic commands, which are small Python scripts that perform various utility operations. In this article, we’ll dive into the five magic commands you need to know to get up and running with IPython. Your productivity will thank you!

Data Analysis with Pandas and Python

Last Updated April 2021

Bestseller
  • 177 lectures
  • All Levels
4.7 (14,802)

Analyze data quickly and easily with Python’s powerful pandas library! All datasets included — beginners welcome! | By Boris Paskhaver

Explore Course

What is IPython?

Let’s review the basics. 

The code that we write is called source code. Source code exists for the programmer’s benefit—our computer’s hardware does not recognize its constructs. The Python interpreter is the software that translates our source code into a language that the computer can understand. 

A shell is a program that allows a user to interact with an operating system or an application. It consists of a prompt (often called the command line) in which we enter and execute text instructions, also known as shell commands.

If you have Python installed on your computer, you can search for the IDLE program in your installation directory. 

Figure 1: The IDLE program in a Python 3.9 installation directory

IDLE is a shell built specifically for the Python language. Inside the application, we can execute lines of Python code. The interpreter immediately translates the code and outputs the result.

Figure 2: Example of the IDLE Shell running on macOS

IPython (Interactive Python) is an expanded version of the IDLE shell. Fernando Pérez, a physicist, developed IPython and released the program in 2001. IPython should not be confused with different versions of Python. It’s more of an expansion pack that increases our productivity with the core language.

In our previous article, we introduced the Jupyter Notebook development environment, a fantastic option for both practicing and writing Python code. A Jupyter Notebook consists of code cells. When we execute a cell, we immediately see its output directly below the code. You’d be surprised how quickly you can pick up a new technology by simply typing commands and seeing their results. 

A Jupyter Notebook uses the IPython shell under its hood. That means we get all the enhancements of IPython inside a beautiful graphical interface. Let’s spin up a fresh Jupyter Notebook and see it in action.

Magic commands

An IPython magic command is a code shortcut. It’s a small chunk of code we add to our program that uses one of IPython’s special features.

Magic commands begin with a % prefix or a %% prefix. When we use a single percentage sign, IPython applies the command to the line of code that follows it. When we use two percentage signs, IPython applies the command to the entire Jupyter Notebook cell.

Let’s dive into five important commands to enhance your productivity in IPython.

1. The %run magic command

Say we have a Python script file with some business logic. Let’s call our file multiply.py.

def multiply(a, b):
    return a * b

Instead of copying and pasting the file’s contents into a cell, we could use the %run magic command to open the Python file and run its code directly in Jupyter Notebook.

In  [1] %run multiply.py

IPython executes the file and imports the Python program’s names (variables, functions, classes, etc.) into the Notebook. We can now invoke the multiply function inside a cell.

In  [2] calculation = multiply(3, 5)
        calculation

Out [2] 15

2. The %timeit magic Command

The %timeit magic command calculates the average execution speed of an expression. To filter out abnormalities, it takes the measurements over many different executions. 

The following example times the execution of a factorial function. IPython executes the line of code one million times!

In  [3]  def factorial(number):
             if number <= 1:
                 return 1
    
         return number * factorial(number - 1)

In  [4] %timeit factorial(10)

1.46 µs ± 49.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

3. The %who_ls magic command

Do you ever forget whether a name exists in your Python program? Or maybe you imported a library or a module from the Python standard library but forgot the alias you assigned to it? The %who_ls magic command lists all names defined in the Jupyter Notebook: variables, modules, functions, classes, and more. It’s a great tool to use after you restart a Notebook and need to verify which cells to re-execute.

In  [5] import datetime as dt
        import pandas as pd

In  [6] %who_ls
        ['calculation', 'dt', 'factorial', 'multiply', 'pd']

4. The %writefile magic command

Jupyter Notebook is a fantastic tool for experimentation, but you’ll likely need to save your code to a plain .py file if you need to run Python manually, such as on a server.

The %%write magic command writes a Notebook cell’s contents to a file. Write the file name right after the command.

In  [7] %%writefile business_logic.py
        def my_business_idea():
            for i in range(10):
                print("Make money")
        
        my_business_idea()

Out [7] Writing business_logic.py

Be careful with this magic command. If you execute the cell again, IPython will overwrite the existing business_logic.py file. 

To append content to the end of an existing file, add the -a (append) flag.

In  [8] %%writefile -a business_logic.py
        def another_business_idea():
            for i in range(10):
                print("Make even more money")
        
        another_business_idea()

Out [8] Appending to business_logic.py

5. The %quickref Magic Command

Curious about what else IPython can do? Execute %quickref to reveal a cheat sheet with a complete list of magic commands and their descriptions.

In  [9] %quickref

Figure 3: A sample of magic commands from the %quickref modal

Summary

We’ve only scratched the surface of what the IPython shell is capable of. The latest version has more than 100 magic commands for you to explore. For a more extensive IPython introduction, head to its official website. I hope it helps you be more productive in your day-to-day Python activities!

Page Last Updated: May 2021

Python students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo

Courses by Boris Paskhaver

Data Analysis with Pandas and Python
Boris Paskhaver
4.7 (14,802)
Bestseller
Learn to Code with Ruby
Boris Paskhaver
4.7 (4,391)
Bestseller
Learn to Code with Python
Boris Paskhaver
4.6 (3,712)
Testing Ruby with RSpec: The Complete Guide
Boris Paskhaver
4.7 (1,032)
Bestseller
Getting Started with React Hooks
Boris Paskhaver
4.6 (353)

Courses by Boris Paskhaver