Skip to content

Instantly share code, notes, and snippets.

@mrroot5
Last active November 16, 2021 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrroot5/6ef9b22f4b7e512c3bd2c4f439cf35b2 to your computer and use it in GitHub Desktop.
Save mrroot5/6ef9b22f4b7e512c3bd2c4f439cf35b2 to your computer and use it in GitHub Desktop.
Crear dataclass en python dinámicamente. Convertir pydantic schema a dataclass. Keywords: python, dataclass, python dataclasss, pydantic, schema, pydantic schema

Intro

Creación dinámica de una dataclass. Puede ser útil, por ejemplo, para convertir un schema de pydantic en un dataclass.

Requisitos

Python >= 3.7.

Ejemplo de uso

  • Importamos make_dataclass.
from dataclasses import make_dataclass
  • Creación dinámica:
MyClass = make_dataclass('MyClass', init=True,
                   fields=[('x', int),
                     'y',
                    ('z', int, field(default=5))],
                   namespace={'add_one': lambda self: self.x + 1})
  • Su dataclass equivalente:
@dataclass(init=True)
class MyClass:
    x: int
    y: 'typing.Any'
    z: int = 5

    def add_one(self):
        return self.x + 1
  • Ejemplo con pydantic (en construcción):
MyClass = make_dataclass('MyClass', init=True,
                   fields=MyPydanticClass.__annotations__,
                   namespace={'add_one': lambda self: self.x + 1})

Fuentes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment