Skip to content

Using TypedDict for templates rendering #355

@dmerejkowsky

Description

@dmerejkowsky

Bug report

What's wrong

So, not sure if it's a bug or not - maybe what I'm trying to achieve is
outside the scope of the typeddjango project. Anyway, here goes.

I have a view_index() view that delegates building the context used
for template rendering to a IndexPresenter class with a get_context()
method:

Here are the relevant snippets (tell me if you need more):

from tying import TypedDict
from models import User, Category

IndexContext = TypedDict("IndexContext", {"user": User, "categories": List[Category]})

class IndexPresenter:
    def __init__(self, user: User):
        self.user = user

    def get_context(self) -> IndexContext:
        categories = Category.objects.all().order_by("name")
        return {"user": self.user, "categories": list(categories)}

@login_required()
def index(request: HttpRequest) -> HttpResponse:
    user = request.user
    presenter = IndexPresenter(user)
    context = presenter.get_context()
    return render(request, "audiotheque/index.pug", context)

You can see I'm using the new TypedDict from Python 3.8

The problem is that mypy complains about the last line:

Argument 3 to "render" has incompatible type  "IndexContext";
expected "Optional[Dict[str, Any]]"

How is that should be

I guess that mypy should see that a TypedDict is compatible with a Dict[str, Any] somehow?

System information

  • OS:
  • python version: 3.8.2
  • django version: 3.0.3
  • mypy version: 0.770
  • django-stubs version: 1.5.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions