Everything now uses bog-standard Python dataclasses, with Pydantic providing validation and type conversion through separate classes using its type adapter feature. It's also possible to define your classes using Pydantic's own model type directly, making the type adapter unnecessary, but I didn't want to do things that way because no actual validation is needed when constructing a Song instance for example. Having Pydantic do its thing only on-demand was preferable. I tried a number of validation libraries before settling on Pydantic for this. It's not the fastest option out there (msgspec is I think), but it makes adding support for third-party types like yarl.URL really easy, it generates a nice clean JSON Schema which is easy enough to adjust to my requirements through its GenerateJsonSchema hooks, and raw speed isn't all that important anyway since this is a single-user desktop program that reads its configuration file once on startup. Also, MessagePack is now mandatory if you're caching to an external service. It just didn't make a whole lot sense to explicitly install mpd-now-playable's Redis or Memcached support and then use pickling with them. With all this fussing around done, I'm probably finally ready to actually use that configuration file to configure new features! Yay!
43 lines
883 B
Python
43 lines
883 B
Python
from typing import Callable
|
|
|
|
from mypy.plugin import ClassDefContext, Plugin
|
|
from mypy.plugins.common import add_attribute_to_class
|
|
|
|
|
|
def add_schema_classvars(ctx: ClassDefContext) -> None:
|
|
api = ctx.api
|
|
cls = ctx.cls
|
|
URL = api.named_type("yarl.URL")
|
|
Adapter = api.named_type(
|
|
"pydantic.type_adapter.TypeAdapter", [api.named_type(cls.fullname)]
|
|
)
|
|
|
|
add_attribute_to_class(
|
|
api,
|
|
cls,
|
|
"id",
|
|
URL,
|
|
final=True,
|
|
is_classvar=True,
|
|
)
|
|
add_attribute_to_class(
|
|
api,
|
|
cls,
|
|
"schema",
|
|
Adapter,
|
|
final=True,
|
|
is_classvar=True,
|
|
)
|
|
|
|
|
|
class SchemaDecoratorPlugin(Plugin):
|
|
def get_class_decorator_hook(
|
|
self, fullname: str
|
|
) -> Callable[[ClassDefContext], None] | None:
|
|
if fullname != "mpd_now_playable.tools.schema.define.schema":
|
|
return None
|
|
return add_schema_classvars
|
|
|
|
|
|
def plugin(version: str) -> type[SchemaDecoratorPlugin]:
|
|
return SchemaDecoratorPlugin
|