Skip to content

Error in printing exception with undefined variable in import statement #1037

@jlumpe

Description

@jlumpe

When making the mistake of using the "python syntax" in an import statement and forgetting to enclose the template name in quotes, and when the name corresponds to an undefined variable, a TemplateNotFound exception is raised with Undefined as the template name and prints an uninformative message.

Expected Behavior

Probably checking the type of the template name expression, and if it's not a string report that instead of TemplateNotFound.

Actual Behavior

Exception prints as

jinja2.exceptions.TemplateNotFound: <exception str() failed>

in Python REPL and

<class 'str'>: (<class 'TypeError'>, TypeError('__str__ returned non-string (type Undefined)',))

in IPython.

Template Code

{% from foo import bar %}

Full Traceback

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/student/anaconda/lib/python3.6/site-packages/jinja2/asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "/Users/student/anaconda/lib/python3.6/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/Users/student/anaconda/lib/python3.6/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/student/anaconda/lib/python3.6/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
  File "/Users/student/anaconda/lib/python3.6/site-packages/jinja2/loaders.py", line 286, in get_source
    raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: <exception str() failed>

In the innermost line raise TemplateNotFound(template), template is Undefined. TemplateNotFound.__str__() just returns self.message, which is also Undefined, so the exact behavior is dependent on what exactly is doing the exception handling/printing.

Granted, this is probably unlikely to happen when loading from actual template files because of the inclusion of a file extension in the name, but I was testing with DictLoader and the keys were just alphanumeric strings. It took a while to figure out what the actual problem was.

Your Environment

  • Python version: 3.6.2
  • Jinja version: 2.10

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions