Get KeyError: '_oh' when running a recursion in jupyter notebook

Dear all,
I have run hundred cells and everything works fine until it runs a recursion. I don’t know whether it is a problem of recursion or not. But the error raise first when I tried to run the below recursion in jupyter notebook.

# Factorial
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

factorial(5)

It raised an error. The error message is as below:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-213-34bd0477e20c> in <module>
      6         return n * factorial(n-1)
      7 
----> 8 factorial(5)

~\Anaconda3\lib\site-packages\IPython\core\displayhook.py in __call__(self, result)
    261             self.write_output_prompt()
    262             format_dict, md_dict = self.compute_format_data(result)
--> 263             self.update_user_ns(result)
    264             self.fill_exec_result(result)
    265             if format_dict:

~\Anaconda3\lib\site-packages\IPython\core\displayhook.py in update_user_ns(self, result)
    199 
    200         # Avoid recursive reference when displaying _oh/Out
--> 201         if result is not self.shell.user_ns['_oh']:
    202             if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
    203                 self.cull_cache()

KeyError: '_oh'

This code has no error when I ran it in Python IDLE. And after that, I cannot show any result unless I use a print() function. For example, a simple cell like this:

a = 1
a

raise the above error. I have to change my code to:

a = 1
print(a)

Any help is welcome. Thank you.

It would be nice if someone here can shed some light on the technical reason behind the different behavior; however, to save others some time investigating, I’ll point out:

  • This is a cross-post with here.
  • As pointed out in the comments in the cross-post this behavior is not reproducible in current Jupyter notebooks or JupyterLab. Running the code in the first code clock works and reports the result with no raised error. No addition of print() is needed.

The raised error specifically says # Avoid recursive reference when displaying _oh/Out, and so it is an issue with the recursion.