biqqles / dataclassy

A fast and flexible reimplementation of data classes
https://pypi.org/project/dataclassy
Mozilla Public License 2.0
82 stars 9 forks source link

Metadata fields? (e.g., SQLAlchemy) #25

Closed playfulpachyderm closed 3 years ago

playfulpachyderm commented 3 years ago

Is there a way to add metadata to the fields? For instance, with the buildin dataclasses module, I use

    title: Optional[str] = field(default=None, metadata={"sa": Column(String)})
    url: Optional[str] = field(default=None, metadata={"sa": Column(String)})

The metadata dict allows SQLAlchemy to read the generated dataclass's annotations and map it automatically. Dataclassy doesn't seem to have the field generator function, so is it possible to attach metadata?

biqqles commented 3 years ago

I admit this is the first time I've seen anyone actually use the metadata parameter! Personally my preference would be to use something that's smart enough to infer everything it needs from the type hint. I'm not sure how practical that is however.

playfulpachyderm commented 3 years ago

I agree, but this is currently the recommended way to combine SQLAlchemy with dataclasses: https://docs.sqlalchemy.org/en/14/orm/mapping_styles.html#example-two-dataclasses-with-declarative-table

biqqles commented 3 years ago

Is there a reason you would rather not use the "imperative table" (example one)? It seems like you would also use this if you were using attrs instead of dataclasses, for example.

playfulpachyderm commented 3 years ago

For some reason it didn't even occur to me to try that (probably because I've always used declarative mappings before I started with dataclasses). That's probably the right answer. Thanks