AnswerDotAI / fastsql

https://answerdotai.github.io/fastsql
Apache License 2.0
34 stars 2 forks source link

Extend dataclass #17

Open Sau1707 opened 1 month ago

Sau1707 commented 1 month ago

If you'd like to extend the @dataclass decorator to allow to add more settings to the table class itself, for example move the "pk='name'" in the class decorator, you can do that by using dataclass_transform imported from the typing module, for instance

from dataclasses import dataclass
from typing import dataclass_transform

@dataclass_transform()
def useTable(pk: str):
    def decorator(cls):
        cls = dataclass(cls)
        cls.__pk__ = pk
        return cls
    return decorator

@useTable("table_1")
class Example:
    name: str
    age: int

ex1 = Example("John", 30)
print(ex1)
# Output: Example(name='John', age=30)

Plus ex1 has all the type hints in the editor as the normal dataclass does.

Sau1707 commented 1 month ago

I was plaing around with this a few months ago but never had time to finish, feel free to take a look and get inspired https://github.com/Sau1707/ezstorage