flask icon indicating copy to clipboard operation
flask copied to clipboard

fix #5729: raise TypeError when @app.template_filter is used without parenthesis

Open Gable-github opened this issue 7 months ago • 4 comments

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_parens in tests/test_templating.py
  • [x] Confirmed pytest and pre-commit both pass

Gable-github avatar May 16 '25 22:05 Gable-github

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.

ThiefMaster avatar May 16 '25 22:05 ThiefMaster

In any case, this should probably be consistently done for template_global, template_test, etc.

ThiefMaster avatar May 16 '25 22:05 ThiefMaster

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.

ThiefMaster avatar May 16 '25 22:05 ThiefMaster

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.

Gable-github avatar May 16 '25 22:05 Gable-github

I've decided I don't want to raise an error on these uses. Thanks for working on this!

davidism avatar Aug 19 '25 17:08 davidism