jupyter / nbformat

Reference implementation of the Jupyter Notebook format
http://nbformat.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
259 stars 153 forks source link

Issue AttributeError: 'list' object has no attribute 'split' nbconvert/filters/strings.py", line 201, in comment_lines return prefix + ("\n" + prefix).join(text.split("\n")) #361

Open ShlomoStept opened 1 year ago

ShlomoStept commented 1 year ago

An error occurs when processing IPython notebook files with 'nbformat': 4 and 'nbformat_minor': 2 (and possibly other versions). The traceback is as follows:

Traceback (most recent call last):

File : "../lib/python3.9/site-packages/nbconvert/exporters/templateexporter.py", line 421, in from_notebook_node output = self.template.render(nb=nb_copy, resources=resources)

File ".../jinja2/environment.py", line 1301, in render

NOTE: The issue arises because cell.source is a list of strings instead of a single string. As a result, the text.split("\n") operation in the comment_lines function (line 201 in nbconvert/filters/strings.py) fails.

One potential solution to this problem could be to add a function before the output = self.template.render(nb=nb_copy, resources=resources) line in the from_notebook_node method (line 421). This function would take nb_copy as an input and modify it as follows:

for cell in nb_copy.cells:
    if isinstance(cell.source, list):
        cell.source = ''.join(cell.source)

Alternatively, a try-except block could be added that only runs this code if an exception is raised.

just for reference the function i used that triggered this error is

    # Step 0 - Convert the file from bytes to string
    file_as_string = file_as_string.decode('utf-8')

    # Step 1 - Get the version of the ipynb file, (a) convert it to JSON format, (b) grab the version
    ipynb_as_json = json.loads(file_as_string)

    # Get the version of the notebook format
    ipynb_version = ipynb_as_json["nbformat"]

    # Normalize the notebook
    n_changes, new_notebook = nbformat.validator.normalize(ipynb_as_json, version=ipynb_version)

    # Step 2 - Load the notebook from a string
    note_book = nbformat.from_dict(new_notebook)

    # Step 3 - Convert the notebook to a Python script
    exporter = PythonExporter()

    python_version, _ = exporter.from_notebook_node(note_book)
...