This is not a pydantic
question, but to explain why am I asking: pydantic.TypeAdapter()
accepts (among many others) all the following type definitions as its argument and can create a working validator for them:
int
int|str
list
list[str|int]
typing.Union[int,str]
typing.Literal[10,20,30]
Example:
>>> validator = pydantic.TypeAdapter(list[str|int]).validate_python
>>> validator([10,20,"stop"])
[10, 20, 'stop']
>>> validator([10,20,None])
(traceback deleted)
pydantic_core._pydantic_core.ValidationError: ...
I want to make a test if an argument is a such type defition. How do I write such test?
- I started with
isinstance(arg, type)
for simple types likeint
orlist
- then I added
isinstance(arg, types.GenericAlias
forlist[str]
etc. - then I realized it does not recognize
int|str
(which itself behaves differently thantyping.Union[int,str]
). Also theLiteral[]
is not recognized … I’m probably on a wrong track.