Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Gable-github
Copy link

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


  • Added test: test_template_filter_requires_parens in tests/test_templating.py
  • Confirmed pytest and pre-commit both pass

@ThiefMaster
Copy link
Member

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
Copy link
Member

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

@ThiefMaster
Copy link
Member

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.

@Gable-github
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

The template_filter decorator doesn't work if you don't pass an argument
2 participants