Validate template tag context argument at definition time, rather than compile time?

If a template tag is defined incorrectly, by not accepting a context argument with takes_context=True:

@register.simple_tag(takes_context=True)
def my_tag():
    pass

An error is only raised when the template is compiled, rather than when the tag is defined as someone may expect. This means there’s extra work done at compile time, which is duplicated each time the tag is used, across multiple templates.

Moving this validation to be done at definition time would likely improve performance. Reading the function signature is already done at definition time, so the performance improvement will likely only be checking the list of arguments, but reporting the error earlier would probably also be a DX improvement.

Interested in what other people think of this before I open a ticket.

3 Likes

This makes sense to me. Especially if the check is cheap enough to avoid hurting startup time much, which I expect it would be.

There is already a method func_supports_parameter in django.utils.inspect which seems to be what is required to implement this.

Also a similar validation is already performed by Signal.connect to ensure that the receiver function supports generic keyword arguments.

A benchmark is required to ensure that this does not slow-down existing applications with lots of custom simple-tags.

Yes, this seems worth it. Did you start working on it @theorangeone ?

I’ve had thoughts and done some poking, but nothing concrete. Given there’s clearly interest, I’ll get a Trac ticket together, and try refining it into a concrete patch.

2 Likes

Trac ticket: