Importing Python Shell Code
Pasting Code Snippets
Section titled “Pasting Code Snippets”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.
Pasting from Standard Python Shell
Section titled “Pasting from Standard Python Shell”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: 0Number: 1Number: 2IPython correctly executes the code, ignoring the foreign prompts.
Pasting from Another IPython Session
Section titled “Pasting from Another IPython Session”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]: 42The 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.