Embedding IPython



The embed() function of IPython module makes it possible to embed IPython in your Python codes namespace. Thereby you can leverage IPython features like object introspection and tab completion, in default Python environment.

(myenv) D:\Projects\python\myenv>py
Python 3.14.2 (tags/v3.14.2:df79316, Dec  5 2025, 17:18:21) [MSC v.1944 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import IPython
>>> IPython.embed()
Python 3.14.2 (tags/v3.14.2:df79316, Dec  5 2025, 17:18:21) [MSC v.1944 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 9.8.0 -- An enhanced Interactive Python. Type '?' for help.
Tip: Use `F2` or %edit with no arguments to open an empty editor with a temporary file.

In [1]:

Python objects present in the global namespace before embedding, will be available to IPython.

>>> num=[1,2,3,4]
>>> import IPython
>>> IPython.embed()
Python 3.14.2 (tags/v3.14.2:df79316, Dec  5 2025, 17:18:21) [MSC v.1944 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 9.8.0 -- An enhanced Interactive Python. Type '?' for help.
Tip: IPython 9.0+ has hooks to integrate AI/LLM completions.

In [1]: num
Out[1]: [1, 2, 3, 4]

In [2]: num.append(5)

In [3]: s = sum(num)

In [4]: exit

>>> num
[1, 2, 3, 4, 5]
>>> s
15
>>>

If new objects are formed while in IPython or previous objects are modified, they will be automatically available to default environment after exiting IPython. Embedded IPython shell doesnt change the state of earlier code or objects.

However, if IPython is embedded in local namespace like inside a function, the objects inside it will not be available once it is closed. Here, we have defined a function add(). Inside add() we invoke IPython and declared a variable. If we try to access variable in IPython after it is closed, NameError exception will be raised.

>>> def add():
...     a = 10
...     import IPython
...     IPython.embed()
...     c = a + b
...     print('addition', c)
...
>>> add()
Python 3.14.2 (tags/v3.14.2:df79316, Dec  5 2025, 17:18:21) [MSC v.1944 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 9.8.0 -- An enhanced Interactive Python. Type '?' for help.
Tip: You can change the editing mode of IPython to behave more like vi, or emacs.

In [1]: b=20

In [2]: exit

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
File <python-input-9>:1

File <python-input-8>:5, in add()

NameError: name 'b' is not defined
>>>
Advertisements