[Feature Request] extra_context -> dataclass

53 views
Skip to first unread message

Arthur

unread,
Apr 6, 2022, 10:06:14 AM4/6/22
to Django developers (Contributions to Django itself)

Hi all!

Currently django views do not accept dataclasses as context.

I stumbled about this because I wanted to do something like this:

@cached_property
def extra_context(self):
    data = MyDataClass(...)
    ...
    return data

Unfortunately, this is unpacked by get_context_data and throws an error because a dataclass can't be iterated (core code):


def get_context_data(self, **kwargs):
    kwargs.setdefault('view', self)
    if self.extra_context is not None:
        kwargs.update(self.extra_context)
    return kwargs


I know I could do a asdict(data)inside the `extra_context` but with the transformation to a dict, I will lose all my typesafety, e.g.:


def get_template_names(self):
    if self.extra_context.somedata:  # << somedata is typed
        ...

A simple check for dataclass would be nice (https://docs.python.org/3/library/dataclasses.html#dataclasses.is_dataclass):


def get_context_data(self, **kwargs):
    kwargs.setdefault('view', self)
    if self.extra_context is not None:
        if is_dataclass(self.extra_context) and not isinstance(self.extra_context, type):
            kwargs.update(asdict(self.extra_context))
        else:
            kwargs.update(self.extra_context)
    return kwargs


Kind regards!

Adam Johnson

unread,
Apr 6, 2022, 12:53:29 PM4/6/22
to Django developers (Contributions to Django itself)
Template contexts are namespaces, for which a dictionary is an ideal type. If you want type safety with dicts, you can use TypedDict in type hints. You haven't presented any advantage to using dataclasses, plus it doesn't seem that inconvenient to add your own wrapper that calls asdict().

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/b43c5655-c44a-4f9b-8503-37366ec7ea5en%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages