How to get the 'execution count' of the most recent execution in IPython or a Jupyter notebook?

Viewed 844

IPython and Jupyter notebooks keep track of an 'execution count'. This is e.g. shown in the prompts for input and output: In[...] and Out[...].

How can you get the latest execution count programmatically?

The variable Out cannot be used for this:

  • Out is a dictionary, with execution counts as keys, but only for those cells that yielded a result; note that not all (cell) executions need to yield a result (e.g. print(...)).

The variable In seems to be usable:

  • In is a list of all inputs; it seems that In[0] is always primed with an empty string, so that you can use the 1-based execution count as index.

However, when using len(In) - 1, in your code, you need to take into account that the execution count seems to be updated before execution of that new code. So, actually, it seems you need to use len(In) - 2 for the execution count of the most recent already completed execution.

Questions:

  • Is there a better way to get the current execution count?
  • Can you rely on the above observations (the 'seems')?
1 Answers

After more digging, I found the (surprisingly simple) answer:

from IPython import get_ipython

ipython = get_ipython()

... ipython.execution_count ...

This does not show up in the IPython documentation, though could (should?) have been mentioned here: https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.interactiveshell.html (I guess attributes are not documented). Here you do find run_line_magic (which was mentioned in a comment to my question).

The way I found this attribute is by defining ipython as above and then doing code completion (TAB) on ipython. (but it does not have documentation).

help(ipython)

gives you documentation about InteractiveShell, and it does mention execution_count (though it does not confirm its purpose):

 |  execution_count
 |      An int trait.
Related