Ephes Blog

Miscellaneous things. Mostly Weeknotes and links I stumbled upon.

Date -

Type Annotations can Cause Unexpected Behavior in Python

, Jochen

Today I learned that type annotations in Python, while being valid code, can sometimes lead to unexpected problems. In a Django view, I had the following line:

def some_view(request):
    ...
    context["form"]: form
    return render(request, some_template, context=context)

This line doesn't raise a SyntaxError because the colon is interpreted as part of a type annotation, which is ignored at runtime. As a result, the line effectively becomes just context["form"], which is a no-op but still valid Python code.


It took me some time to figure out why {% if form.field.errors %} used later on was was always false. 🤦‍♂️