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().

On Wed, Apr 6, 2022 at 2:48 PM Arthur <arthur.b...@sdox.io> wrote:

> 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!
>
> --
> 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-developers+unsubscr...@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
> <https://groups.google.com/d/msgid/django-developers/b43c5655-c44a-4f9b-8503-37366ec7ea5en%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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-developers+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/CAMyDDM2SfOb6K_eVkdNaiSdcJoZjqnKUAuA0pGfs%3DD3WqD0Q6Q%40mail.gmail.com.
  • [Fe... Arthur
    • ... 'Adam Johnson' via Django developers (Contributions to Django itself)

Reply via email to