Search code examples
pythonpandasdataframeprettytable

Local variable 'body' referenced before assignment - Python - build_table


Trying to send an email with Python build table. However, I'm experiencing the following error when I output the dataframe as a table. What is the issue here?

from pretty_html_table import build_table

riskDataFrame  = pd.read_sql(query, sql_conn)   
outputTable = build_table(riskDataFrame, 'blue_light')

Error is Unknown Error local variable 'body' referenced before assignment

File "C:\Python-3.9\lib\site-packages\pretty_html_table\pretty_html_table.py", line 141, in build_table body = body + """

""" UnboundLocalError: local variable 'body' referenced before assignment


Solution

  • According to build_table() source code, variable body is created inside a loop. The loop is entered if the DataFrame passed in the argument is not empty

    This means if you pass an empty DataFrame object in the parameter, the method build_table() never enters the loop and thus body remains undefined.

    Check if your df is empty before passing it to build_table()