flask icon indicating copy to clipboard operation
flask copied to clipboard

`template_filter` decorator typing does not support custom filters with multiple arguments

Open luyizhao opened this issue 5 years ago • 2 comments

template_filter decorator typing does not support custom filters that take in multiple arguments. Consider:

from flask import Flask


app = Flask(__name__)


@app.template_filter('foo_bar')
def foo_bar_filter(foo, bar):
    return f'{foo} {bar}'

mypy will return the following error message:

error: Argument 1 has incompatible type "Callable[[Any, Any], Any]"; expected "Callable[[Any], str]"  [arg-type]

As custom filters with multiple arguments are supported by Jinja (https://jinja.palletsprojects.com/en/3.0.x/api/#custom-filters), I think this typing error is a false positive.

Environment:

  • Python version: 3.6.13
  • Flask version: 2.0.1
  • Mypy version: 0.812

luyizhao avatar Aug 05 '21 02:08 luyizhao

I can't reproduce this issue. Running mypy on the example code succeeds. Adding reveal_type(app.template_filter) shows:

example.py:11: note: Revealed type is 'def (name: Union[builtins.str, None] =) -> def (def (*Any, **Any) -> Any) -> def (*Any, **Any) -> Any'

Which indicates that any number of positional and keyword arguments are accepted.

davidism avatar Aug 06 '21 02:08 davidism

Ah, ok so dug into this a bit more and it looks like the typing for the jinja decorators changed in: https://github.com/pallets/flask/commit/8e589daaf2cec6a10262b8ff88801127f2fa14fd which isn't in 2.0.1.

So mypy runs fine on main and the issue will be fixed in next release 👍

luyizhao avatar Aug 06 '21 14:08 luyizhao