Search code examples
pythonsqlalchemywarningspypdf

Python formatWarning and cross-package errors


Okay, I am confused. I am using two Python packages - PyPDF2 and SQLAlchemy. SQLAlchemy is raising a warning using python's warning.warn(), and somehow calling a formatWarning() function in PyPDF2, which also uses python's warning.warn().

Is this an error in SQLAlchemy or PyPDF2?

How does this even happen - is formatWarning some special function?

PyPDF2 defines it as:

#custom implementation of warnings.formatwarning
def formatWarning(message, category, filename, lineno, line=None):
    file = filename.replace("/", "\\").rsplit("\\", 1)[1] # find the file name
    return "%s: %s [%s:%s]\n" % (category.__name__, message, file, lineno)

My error stack is -

  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.7-py2.7-linux-x86_64.egg/sqlalchemy/orm/strategies.py", line 613, in _emit_lazyload
    % self.parent_property)

  File "/usr/local/lib/python2.7/dist-packages/SQLAlchemy-0.9.7-py2.7-linux-x86_64.egg/sqlalchemy/util/langhelpers.py", line 1205, in warn
    warnings.warn(msg, exc.SAWarning, stacklevel=stacklevel)

  File "/usr/local/lib/python2.7/dist-packages/PyPDF2/pdf.py", line 817, in _showwarning
    file.write(formatWarning(message, category, filename, lineno, line))

  File "/usr/local/lib/python2.7/dist-packages/PyPDF2/utils.py", line 59, in formatWarning
    file = filename.replace("/", "\\").rsplit("\\", 1)[1] # find the file name

  IndexError: list index out of range

Solution

  • It appears this was an old error in the package PyPDF2, where it was overwriting python utils._formatwarning:

    warnings.formatwarning = utils._formatwarning
    

    Recent releases appear to have fixed this, updating to the latest fixed the issue.