plotly / plotly.py

The interactive graphing library for Python :sparkles: This project now includes Plotly Express!
https://plotly.com/python/
MIT License
16.34k stars 2.56k forks source link

Exception caused when using `plotly.express.timeline` when `kaleido` is installed #4885

Open namurphy opened 1 week ago

namurphy commented 1 week ago

I am attempting to reproduce an example for creating a Gantt chart with plotly.express.timeline, but have been getting an exception when attempting to show the plot. When I ran this example in an environment where kaleido was not installed, the exception did not happen.

Steps to reproduce

[!NOTE] This reproduced the error for me on RHEL 8.10, but I was not able to reproduce the error on Ubuntu 22.04.

I'm using uv to do this. I created a file called gantt.py with the following:

# /// script
# requires-python = ">=3.13"
# dependencies = [
#     "kaleido",
#     "numpy",
#     "pandas",
#     "plotly",
# ]
# ///

import plotly.express as px
import pandas as pd

def main() -> None:
    """Create a Gantt chart."""

    df = pd.DataFrame([
        dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
        dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'),
        dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30')
    ])

    fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task")
    fig.update_yaxes(autorange="reversed") # otherwise tasks are listed from the bottom up
    fig.show()  # exception occurs when attempting to show plot

if __name__ == "__main__":
    main()

I then ran

uv run gantt.py

I then get the following error (shortening some of the paths for brevity):


Reading inline script metadata from `gantt.py`
Traceback (most recent call last):
  File ".../gantt.py", line 28, in <module>
    main()
    ~~~~^^
  File "../gantt.py", line 25, in main
    fig.show()
    ~~~~~~~~^^
  File ".../.cache/uv/archive-v0/O5onHXOSLx_hZOrhGrYG4/lib/python3.13/site-packages/plotly/basedatatypes.py", line 3410, in show
    return pio.show(self, *args, **kwargs)
           ^^^^^^^^
  File ".../.cache/uv/archive-v0/O5onHXOSLx_hZOrhGrYG4/lib/python3.13/site-packages/_plotly_utils/importers.py", line 36, in __getattr__
    class_module = importlib.import_module(rel_module, parent_name)
  File ".../.local/share/uv/python/cpython-3.13.0-linux-x86_64-gnu/lib/python3.13/importlib/__init__.py", line 88, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 1022, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "...v/archive-v0/O5onHXOSLx_hZOrhGrYG4/lib/python3.13/site-packages/plotly/io/_renderers.py", line 9, in <module>
    from plotly.io._base_renderers import (
    ...<18 lines>...
    )
  File ".../.cache/uv/archive-v0/O5onHXOSLx_hZOrhGrYG4/lib/python3.13/site-packages/plotly/io/_base_renderers.py", line 9, in <module>
    from plotly.io import to_json, to_image, write_image, write_html
  File "<frozen importlib._bootstrap>", line 1412, in _handle_fromlist
  File ".../.cache/uv/archive-v0/O5onHXOSLx_hZOrhGrYG4/lib/python3.13/site-packages/_plotly_utils/importers.py", line 36, in __getattr__
    class_module = importlib.import_module(rel_module, parent_name)
  File ".../.local/share/uv/python/cpython-3.13.0-linux-x86_64-gnu/lib/python3.13/importlib/__init__.py", line 88, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../.cache/uv/archive-v0/O5onHXOSLx_hZOrhGrYG4/lib/python3.13/site-packages/plotly/io/_kaleido.py", line 10, in <module>
    scope = PlotlyScope()
  File ".../.cache/uv/archive-v0/O5onHXOSLx_hZOrhGrYG4/lib/python3.13/site-packages/kaleido/scopes/plotly.py", line 64, in __init__
    elif "snap" in path:
         ^^^^^^^^^^^^^^
TypeError: argument of type 'NoneType' is not iterable

However, when I remove "kaleido" from the dependencies, the script worked fine.

Steps to reproduce on Google Colab

First I made sure packages were installed:

!pip install numpy pandas kaleido plotly

Then in the next cell I ran:

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
    dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'),
    dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30')
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task")
fig.update_yaxes(autorange="reversed") # otherwise tasks are listed from the bottom up
fig.show()

...which led to the following exception:

TypeError                                 Traceback (most recent call last)
[<ipython-input-2-b0c63c1fc3d3>](https://localhost:8080/#) in <cell line: 12>()
     10 fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task")
     11 fig.update_yaxes(autorange="reversed") # otherwise tasks are listed from the bottom up
---> 12 fig.show()

15 frames
[/usr/local/lib/python3.10/dist-packages/kaleido/scopes/plotly.py](https://localhost:8080/#) in __init__(self, plotlyjs, mathjax, topojson, mapbox_access_token, debug, tmp_path, **kwargs)
     62         if tmp_path:
     63             temp_args = dict(dir=self.tmp_path)
---> 64         elif "snap" in path:
     65             temp_path = Path.home()
     66             if self.debug:

TypeError: argument of type 'NoneType' is not iterable

Many thanks!

gvwilson commented 1 week ago

thanks @namurphy - can you please run uv pip list and paste the output into a comment here so we can see what versions of various packages you have? thanks - @gvwilson

namurphy commented 6 days ago

I knew I was forgetting something! 😅 These are the results of doing uv pip list on an environment in which I'm getting the error. The most relevant versions are: plotly==5.24.1 and kaleido==0.4.1.

Using Python 3.13.0 environment at /home/namurphy/.venv
Package                       Version
----------------------------- -------------------
aioftp                        0.23.1
aiohappyeyeballs              2.4.3
aiohttp                       3.10.10
aiosignal                     1.3.1
alabaster                     0.7.16
anyio                         4.6.2.post1
argcomplete                   3.5.1
argon2-cffi                   23.1.0
argon2-cffi-bindings          21.2.0
arrow                         1.3.0
asciitree                     0.3.3
asteval                       1.0.5
astropy                       6.1.5
astropy-healpix               1.0.3
astropy-iers-data             0.2024.11.4.0.33.34
asttokens                     2.4.1
async-lru                     2.0.4
async-timeout                 5.0.1
attrs                         24.2.0
babel                         2.16.0
beautifulsoup4                4.12.3
binaryornot                   0.4.4
bleach                        6.2.0
cached-property               2.0.1
certifi                       2024.8.30
cffi                          1.17.1
cfgv                          3.4.0
chardet                       5.2.0
charset-normalizer            3.4.0
choreographer                 0.99.6
click                         8.1.7
clize                         5.0.2
cloudpickle                   3.1.0
colorlog                      6.9.0
comm                          0.2.2
contourpy                     1.3.0
cookiecutter                  2.6.0
coverage                      7.6.4
cycler                        0.12.1
dask                          2024.10.0
debugpy                       1.8.7
decorator                     5.1.1
defusedxml                    0.7.1
dill                          0.3.9
distlib                       0.3.9
docutils                      0.21.2
execnet                       2.1.1
executing                     2.1.0
fasteners                     0.19
fastjsonschema                2.20.0
filelock                      3.16.1
fonttools                     4.54.1
fqdn                          1.5.1
frozenlist                    1.5.0
fsspec                        2024.10.0
h11                           0.14.0
h5py                          3.12.1
httpcore                      1.0.6
httpx                         0.27.2
hypothesis                    6.117.0
identify                      2.6.1
idna                          3.10
imageio                       2.36.0
imagesize                     1.4.1
iniconfig                     2.0.0
ipykernel                     6.29.5
ipython                       8.29.0
ipywidgets                    8.1.5
isoduration                   20.11.0
jedi                          0.19.1
jinja2                        3.1.4
json5                         0.9.25
jsonpointer                   3.0.0
jsonschema                    4.23.0
jsonschema-specifications     2024.10.1
jupyter                       1.1.1
jupyter-client                8.6.3
jupyter-console               6.6.3
jupyter-core                  5.7.2
jupyter-events                0.10.0
jupyter-lsp                   2.2.5
jupyter-server                2.14.2
jupyter-server-terminals      0.5.3
jupyterlab                    4.2.5
jupyterlab-pygments           0.3.0
jupyterlab-server             2.27.3
jupyterlab-widgets            3.0.13
kaleido                       0.4.1
kiwisolver                    1.4.7
latexcodec                    3.0.0
lazy-loader                   0.4
lmfit                         1.3.2
locket                        1.0.0
markdown-it-py                3.0.0
markupsafe                    3.0.2
matplotlib                    3.9.2
matplotlib-inline             0.1.7
mdurl                         0.1.2
mistune                       3.0.2
mpl-animators                 1.2.0
mpmath                        1.3.0
multidict                     6.1.0
mypy                          1.13.0
mypy-extensions               1.0.0
nbclient                      0.10.0
nbconvert                     7.16.4
nbformat                      5.10.4
nbsphinx                      0.9.5
nest-asyncio                  1.6.0
networkx                      3.4.2
nodeenv                       1.9.1
notebook                      7.2.2
notebook-shim                 0.2.4
nox                           2024.10.9
numcodecs                     0.13.1
numpy                         2.1.3
numpydoc                      1.8.0
od                            2.0.2
overrides                     7.7.0
packaging                     24.1
pandas                        2.2.3
pandocfilters                 1.5.1
parfive                       2.1.0
parso                         0.8.4
partd                         1.4.2
pexpect                       4.9.0
pillow                        11.0.0
plasmapy                      2024.10.0
platformdirs                  4.3.6
plotly                        5.24.1
pluggy                        1.5.0
pre-commit                    4.0.1
prometheus-client             0.21.0
prompt-toolkit                3.0.48
propcache                     0.2.0
psutil                        6.1.0
ptyprocess                    0.7.0
pure-eval                     0.2.3
pybtex                        0.24.0
pybtex-docutils               1.0.3
pycparser                     2.22
pyerfa                        2.0.1.4
pygments                      2.18.0
pyparsing                     3.2.0
pytest                        8.3.3
pytest-cov                    6.0.0
pytest-datadir                1.5.0
pytest-filter-subpackage      0.2.0
pytest-regressions            2.5.0
pytest-rerunfailures          14.0
pytest-xdist                  3.6.1
python-dateutil               2.9.0.post0
python-gantt                  0.6.0
python-json-logger            2.0.7
python-slugify                8.0.4
pytz                          2024.2
pyyaml                        6.0.2
pyzmq                         26.2.0
referencing                   0.35.1
reproject                     0.14.0
requests                      2.32.3
rfc3339-validator             0.1.4
rfc3986-validator             0.1.1
rich                          13.9.4
rpds-py                       0.21.0
scikit-image                  0.24.0
scipy                         1.14.1
send2trash                    1.8.3
setuptools                    75.3.0
sigtools                      4.0.1
six                           1.16.0
sniffio                       1.3.1
snowballstemmer               2.2.0
sortedcontainers              2.4.0
soupsieve                     2.6
sphinx                        7.3.7
sphinx-changelog              1.6.0
sphinx-codeautolink           0.15.2
sphinx-collapse               0.1.3
sphinx-copybutton             0.5.2
sphinx-gallery                0.18.0
sphinx-hoverxref              1.4.1
sphinx-issues                 5.0.0
sphinx-notfound-page          1.0.4
sphinx-reredirects            0.1.5
sphinx-rtd-theme              3.0.1
sphinx-tabs                   3.4.7
sphinxcontrib-applehelp       2.0.0
sphinxcontrib-bibtex          2.6.3
sphinxcontrib-devhelp         2.0.0
sphinxcontrib-globalsubs      0.1.2
sphinxcontrib-htmlhelp        2.1.0
sphinxcontrib-jquery          4.1
sphinxcontrib-jsmath          1.0.1
sphinxcontrib-qthelp          2.0.0
sphinxcontrib-serializinghtml 2.0.0
sphinxemoji                   0.3.1
stack-data                    0.6.3
sunpy                         6.0.3
svgwrite                      1.4.3
tabulate                      0.9.0
tenacity                      9.0.0
terminado                     0.18.1
text-unidecode                1.3
tifffile                      2024.9.20
tinycss2                      1.4.0
tomli                         2.0.2
toolz                         1.0.0
tornado                       6.4.1
towncrier                     24.8.0
tqdm                          4.67.0
traitlets                     5.14.3
types-python-dateutil         2.9.0.20241003
typing-extensions             4.12.2
tzdata                        2024.2
uncertainties                 3.2.2
unidecode                     1.3.8
uri-template                  1.3.0
urllib3                       2.2.3
virtualenv                    20.27.1
voila                         0.5.8
wcwidth                       0.2.13
webcolors                     24.8.0
webencodings                  0.5.1
websocket-client              1.8.0
websockets                    13.1
widgetsnbextension            4.0.13
wrapt                         1.16.0
xarray                        2024.10.0
xrtpy                         0.4.1
yarl                          1.17.1
zarr                          2.18.3