Skip to content

Importing Python Shell Code

IPython is designed to handle code pasted directly from standard Python (>>>, ...) or other IPython (In [...], ...:) sessions. It intelligently filters out these prompt prefixes, allowing you to easily copy and paste code examples or snippets from tutorials, documentation, or previous sessions.

Imagine you have the following code snippet copied from a standard Python REPL session:

>>> for i in range(3):
... print(f"Number: {i}")
...

You can paste this entire block, including the >>> and ... prompts, directly into an IPython prompt or a Jupyter cell:

In [1]: >>> for i in range(3):
...: ... print(f"Number: {i}")
...: ...
Number: 0
Number: 1
Number: 2

IPython correctly executes the code, ignoring the foreign prompts.

Similarly, you can copy code, including the In [...] and ...: prompts, from one IPython session (or notebook) to another.

Consider this code defined in one IPython instance:

# --- Copied from another session ---
In [5]: def multiply(a, b):
...: """Returns the product of a and b."""
...: return a * b
...:

Pasting this into a new IPython session:

In [1]: In [5]: def multiply(a, b):
...: ...: """Returns the product of a and b."""
...: ...: return a * b
...: ...:
In [2]: multiply(6, 7)
Out[2]: 42

The function definition is correctly parsed and executed, making it ready for use in the new session. This feature significantly streamlines the process of sharing and reusing interactive code snippets.