Skip to content

Automatic init with dataclasses #30

@binyamin555

Description

@binyamin555

Introduction

The following syntax is really neat and useful.

from dataclasses import dataclass

from pydom import Component


@dataclass
class Profile(Component):
  name: str
  age: int

This syntax eliminates the need for writing the __init__ function and also allows for the other features found in Python dataclasses.

The Problem

Now, I have my application built with FastAPI and I added a custom encoder as described here.

When trying to return this component directly from a FastAPI route, it is automatically returned as JSON.

This is because FastAPI first checks if the result is a dataclass, and then directly returns it as a JSON, skipping the rest of the encoders. This, of course, makes sense, because dataclasses are basically data records.

Possible Solution

It'd be nice if you could add your own dataclass decorator for components.
Of course, it should be named something else, since it's job is mainly to generate the __init__ function (although, adding support for frozen and slots could also be useful).

In terms of typing, using this decorator from the typing library will help with proper type hints.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions