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

Cannot introspect generic structs, possibly bug in python stdlib. #666

Closed aspizu closed 2 months ago

aspizu commented 2 months ago

Description

If you use

from __future__ import annotations

and define a generic struct, type alias or anything with the new syntax in python 3.12

then typing.get_type_hints() will fail.

this makes msgspec.inspect.type_info() fail too.

Python 3.12.1 (main, Jan  8 2024, 05:57:25) [Clang 17.0.6 ] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import annotations
>>>
>>> import msgspec
>>>
>>> class A[T](msgspec.Struct):
...   v: T
...
>>> A(1)
A(v=1)
>>> msgspec.inspect.type_info(A)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/aspizu/Documents/Projects/reproca/.venv/lib/python3.12/site-packages/msgspec/inspect.py", line 629, in type_info
    return multi_type_info([type])[0]
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/aspizu/Documents/Projects/reproca/.venv/lib/python3.12/site-packages/msgspec/inspect.py", line 598, in multi_type_info
    return _Translator(types).run()
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/aspizu/Documents/Projects/reproca/.venv/lib/python3.12/site-packages/msgspec/inspect.py", line 744, in run
    MsgpackDecoder(Tuple[self.types])
  File "/home/aspizu/Documents/Projects/reproca/.venv/lib/python3.12/site-packages/msgspec/_utils.py", line 130, in get_class_annotations
    value = typing._eval_type(value, cls_locals, cls_globals)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/aspizu/.rye/py/cpython@3.12.1/install/lib/python3.12/typing.py", line 400, in _eval_type
    return t._evaluate(globalns, localns, recursive_guard)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/aspizu/.rye/py/cpython@3.12.1/install/lib/python3.12/typing.py", line 907, in _evaluate
    eval(self.__forward_code__, globalns, localns),
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 1, in <module>
NameError: name 'T' is not defined
aspizu commented 2 months ago

https://github.com/python/cpython/issues/114053

Known issue.