Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - get_type_hints for generic type

Assume the following class definition,

import typing
from dataclasses import dataclass

T1 = typing.TypeVar('T1')
T2 = typing.TypeVar('T2')

@dataclass
class Test(Generic[T1, T2]):
  some_property: T2
  some_other_property: T1

I would like to get the type hints of a specific bound version of this class, something like

# I would like to get back: {'some_property': str, 'some_other_property': int}
hints = typing.get_type_hints(Test[int,str])

Unfortunately, this don't work in python 3.9, raising a type error "Test[int,str] is not a module, class, method or function". Now, I could do something like

hints = typing.get_type_hints(typing.get_origin(Test[int,str]))

However, in that case, some_property and some_other_properties are returned as TypeVars, rather than specific bound types (int and str).

Binding these manually seems a little annoying; Test[int,str] is of type typing._GenericAlias, which seems to have a property _ _ args _ _ which is [int, str]. I could in theory try to bind them back to the type vars in the order in which they appear first from get_type_hints(get_origin()), but I'm not sure if that is reliable.

Is there any equivalent of get_type_hints that would return fully bound type hints? Or any reasonable other way of doing this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...