jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML
https://jcristharif.com/msgspec/
BSD 3-Clause "New" or "Revised" License
2.3k stars 67 forks source link

Add support for `typing.TypeAliasType` #579

Closed wikiped closed 10 months ago

wikiped commented 11 months ago

Description

Currently (msgspec version 0.18.4, python 3.12) the following:

import msgspec as ms
from typing import Annotated

NonEmptyStringAlias = Annotated[str, ms.Meta(min_length=1)]
type NonEmptyStringTypeAlias = Annotated[str, ms.Meta(min_length=1)]

class A(ms.Struct):
    name: NonEmptyStringAlias

class T(ms.Struct):
    name: NonEmptyStringTypeAlias

print(ms.json.decode(ms.json.encode(A('test')), type=A))

print(ms.json.decode(ms.json.encode(T('test')), type=T))

Will fail on the last line:

A(name='test')
...
TypeError: Type 'NonEmptyStringTypeAlias' is not supported

Considering that:

print(type(NonEmptyStringTypeAlias))
# typing.TypeAliasType

print(type(NonEmptyStringAlias))
# typing._AnnotatedAlias

NonEmptyStringTypeAlias.__value__ is NonEmptyStringAlias
# True

Would it make sense to add support for the typing.TypeAliasType which is created with type statements (since python 3.12)?

jcrist commented 11 months ago

Sure, this is definitely in scope. Adding support for TypeAliasType instances should be fairly straightforward, with the exception of recursive alias definitions (these would require a major refactor of msgspec's internals).