fix #5729: raise TypeError when @app.template_filter is used without parenthesis
Raise a clear TypeError when @app.template_filter is used without parentheses.
This prevents silent failures when users mistakenly write @app.template_filter instead of @app.template_filter(), which previously led to confusing Jinja2 errors as mentioned by @alexwlchan like:
jinja2.exceptions.TemplateAssertionError: No filter named 'double'
when app.py is, for example,
from flask import Flask, render_template_string
app = Flask(__name__)
@app.template_filter
def double(x):
return x * 2
@app.route("/")
def index():
return render_template_string("2 times 2 is {{ 2 | double }}")
Note:
reason i did it this way and not accept when its just @app.template_filter is because it aligns with the behavior of other Flask decorators such as @app.route, which already enforce required parentheses when arguments are expected.
fixes #5729
- [x] Added test:
test_template_filter_requires_parensintests/test_templating.py - [x] Confirmed
pytestandpre-commitboth pass
I don't think this is the best solution... it's quite common in the Python world that decorators where all arguments are optional are "smart" and can be used both with and without parentheses.
In any case, this should probably be consistently done for template_global, template_test, etc.
Looks like we don't have any other cases where we have "smart" decorators... so maybe no need to start introducing them now. Anyway, I'll let @davidism decide what option he prefers.
Thats what I was considering as well. but i realised that i would probably need to change all the others for consistency too.
Maybe that could be a next step i could look into as a new issue.
I've decided I don't want to raise an error on these uses. Thanks for working on this!