Turn off auto-conversion to string of jinja2 expressions

244 views Asked by At

I have an application that makes heavy use of jinja2. Sometimes, I mess up and return a non-string from a filter. (or I fall through all my branch conditions and return None) Jinja then dutifully converts whatever it is I gave it to a string.

I would like Jinja to not do that. I would like Jinja to instead throw an exception, crash, really, just anything to tell me something has gone wrong. How can I do that?

1

There are 1 answers

0
kindall On

You might write a decorator that checks the return value of your filters, and raises an exception if it's not a string. For bonus points, you can have it check __debug__ so it is stripped out in production for zero performance impact in those situations.

import functools

def must_return_str(func):

    if not __debug__: return func

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        ret = func(*args, **kwargs)
        if isinstance(ret, str):
            return ret
        raise TypeError(func.__name__ + " did not return a string")

    return wrapper

@must_return_str
def foo():
    return

foo()

Downside is you must apply it to every function you wish to protect in this way. I don't know much about Jinja to be honest, but you could write a function to apply this decorator to every function in a module, or something of the sort, so you wouldn't need to manually write @must_return_str repeatedly.