Repository: plotly/plotly.py

Issue:
IFrame renderer throws exception on plots in the first cell
Symptom: when running the following conversion on a notebook that produces a plot in the first cell:
```
PLOTLY_RENDERER=iframe_connected jupyter nbconvert --execute --to html --no-input my_notebook.ipynb
```
the following error is received:
```
File ~/.virtualenvs/myenv/lib/python3.9/site-packages/plotly/io/_base_renderers.py:612, in IFrameRenderer.build_filename(self)
    610 def build_filename(self):
    611     ip = IPython.get_ipython() if IPython else None
--> 612     cell_number = list(ip.history_manager.get_tail(1))[0][1] + 1 if ip else 0
    613     filename = "{dirname}/figure_{cell_number}.html".format(
    614         dirname=self.html_directory, cell_number=cell_number
    615     )
    616     return filename

IndexError: list index out of range
```

The iframe renderer saves plots to a separate file and the filename is supposed to be based off the current cell number. The [line of code](https://github.com/plotly/plotly.py/blob/00c18fd0d09a21f7d0f54c383ff5258fe1ff7d28/packages/python/plotly/plotly/io/_base_renderers.py#L612) that retrieves this cell number makes use of the IPython HistoryManager.get_tail method which, by default, returns the *already executed* cells, not the currently executing cell.  When within the first cell it therefore returns an empty list and this is what causes the 'list index our of range'. The fix is very simple: add include_latest=True to the get_tail call so that the currently executing cell is returned instead of the previous one.

Meanwhile a simple workaround is to always include a cell that does not produce a plot at the start of the notebook.

iframe renderer fails in JupyterLab
If you run the following code in a JupyterLab cell:
```
import plotly.express as px
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [3, 4, 5]})
fig = px.line(df, x='A', y='B')
fig.show(renderer="iframe")
```

You get the following error:
```
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[8], line 5
      3 df = pd.DataFrame({'A': [1, 2, 3], 'B': [3, 4, 5]})
      4 fig = px.line(df, x='A', y='B')
----> 5 fig.show(renderer="iframe")

File ~/temps/2023-01-22-1674410931/venv/lib/python3.9/site-packages/plotly/basedatatypes.py:3390, in BaseFigure.show(self, *args, **kwargs)
   3357 """
   3358 Show a figure using either the default renderer(s) or the renderer(s)
   3359 specified by the renderer argument
   (...)
   3386 None
   3387 """
   3388 import plotly.io as pio
-> 3390 return pio.show(self, *args, **kwargs)

File ~/temps/2023-01-22-1674410931/venv/lib/python3.9/site-packages/plotly/io/_renderers.py:388, in show(fig, renderer, validate, **kwargs)
    385 fig_dict = validate_coerce_fig_to_dict(fig, validate)
    387 # Mimetype renderers
--> 388 bundle = renderers._build_mime_bundle(fig_dict, renderers_string=renderer, **kwargs)
    389 if bundle:
    390     if not ipython_display:

File ~/temps/2023-01-22-1674410931/venv/lib/python3.9/site-packages/plotly/io/_renderers.py:296, in RenderersConfig._build_mime_bundle(self, fig_dict, renderers_string, **kwargs)
    293             if hasattr(renderer, k):
    294                 setattr(renderer, k, v)
--> 296         bundle.update(renderer.to_mimebundle(fig_dict))
    298 return bundle

File ~/temps/2023-01-22-1674410931/venv/lib/python3.9/site-packages/plotly/io/_base_renderers.py:570, in IFrameRenderer.to_mimebundle(self, fig_dict)
    567     iframe_height = str(525 + iframe_buffer) + "px"
    569 # Build filename using ipython cell number
--> 570 filename = self.build_filename()
    572 # Make directory for
    573 try:

File ~/temps/2023-01-22-1674410931/venv/lib/python3.9/site-packages/plotly/io/_base_renderers.py:613, in IFrameRenderer.build_filename(self)
    611 ip = IPython.get_ipython() if IPython else None
    612 if ip:
--> 613     cell_number = next(ip.history_manager.get_tail(1), (0, -1, ""))[1] + 1
    614 else:
    615     cell_number = 0

TypeError: 'list' object is not an iterator
```

If you remove `renderer="iframe"`, this completes correctly. 

Relevant versions `pip list | grep -E 'pandas|jupyter|plotly'`:
```
jupyter_client           7.4.9
jupyter_core             5.1.3
jupyter-events           0.6.3
jupyter_server           2.1.0
jupyter_server_terminals 0.4.4
jupyterlab               3.5.2
jupyterlab-pygments      0.2.2
jupyterlab_server        2.19.0
pandas                   1.5.3
plotly                   5.12.0
```

I have verified this bug is reproducible on both Mac Safari and Mac Chrome.

Let me know if any other additional information is helpful!



Discussion:
To be explicit, the fix that worked for me locally was to change this line:
```
cell_number = list(ip.history_manager.get_tail(1))[0][1] + 1 if ip else 0
```
to:
```
cell_number = list(ip.history_manager.get_tail(1, include_latest=True))[0][1] + 1 if ip else 0
```
Hi @gokikamukow, many thanks for finding the actual reason behind this bug! 
It would be nice if this fix could be integrated into Plotly.py :)


Resolving patch:
diff --git a/packages/python/plotly/plotly/io/_base_renderers.py b/packages/python/plotly/plotly/io/_base_renderers.py
--- a/packages/python/plotly/plotly/io/_base_renderers.py
+++ b/packages/python/plotly/plotly/io/_base_renderers.py
@@ -609,11 +609,10 @@ def to_mimebundle(self, fig_dict):
 
     def build_filename(self):
         ip = IPython.get_ipython() if IPython else None
-        if ip:
-            cell_number = next(ip.history_manager.get_tail(1), (0, -1, ""))[1] + 1
-        else:
+        try:
+            cell_number = list(ip.history_manager.get_tail(1))[0][1] + 1 if ip else 0
+        except Exception:
             cell_number = 0
-
         return "{dirname}/figure_{cell_number}.html".format(
             dirname=self.html_directory, cell_number=cell_number
         )


Test patch: