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.01k stars 59 forks source link

Allow passing custom globals to use when converting dataclasses #704

Open provinzkraut opened 2 weeks ago

provinzkraut commented 2 weeks ago

Description

Currently there's an issue where msgspec cannot convert a dataclass that contains forward references. This isn't unusual or msgspec specific, it is however a problem when trying to use msgspec to convert dataclasses that you don't have control over, i.e. cannot change the fact that they contain forward references.

# a.py
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING

if TYPE_CHECKING:
 from typing import Any

@dataclass
class Some:
 value: Any
# b.py
from a import Some
import msgspec

# this fails with  NameError: name 'Any' is not defined
msgspec.convert({"value": "something"}, type=Some)

A simple interface that would allow passing a custom set of globals to the internally used get_class_annotations would do the trick I think. Or is there another solution here that I'm not aware of? :)