Open kevinhikaruevans opened 4 months ago
From the source of the function https://github.com/ilevkivskyi/typing_inspect/blob/master/typing_inspect.py#L261-L275:
NEW_TYPING = sys.version_info[:3] >= (3, 7, 0) # it's always True, since fastapi-utils requires >=3.7
def is_classvar(tp):
"""Test if the type represents a class variable. Examples::
is_classvar(int) == False
is_classvar(ClassVar) == True
is_classvar(ClassVar[int]) == True
is_classvar(ClassVar[List[T]]) == True
"""
if NEW_TYPING:
return (tp is ClassVar or
isinstance(tp, typingGenericAlias) and tp.__origin__ is ClassVar)
elif WITH_CLASSVAR:
return type(tp) is _ClassVar
else:
return False
we get that to solve this problem we need only a few lines instead of the undocumented requirement of typing_inspect
:
from typing import _GenericAlias
if sys.version_info[:3] >= (3, 9, 0):
from typing import _SpecialGenericAlias
typingGenericAlias = (_GenericAlias, _SpecialGenericAlias, types.GenericAlias)
else:
typingGenericAlias = (_GenericAlias,)
def is_classvar(tp):
"""Test if the type represents a class variable. Examples::
is_classvar(int) == False
is_classvar(ClassVar) == True
is_classvar(ClassVar[int]) == True
is_classvar(ClassVar[List[T]]) == True
"""
return tp is ClassVar or isinstance(tp, typingGenericAlias) and tp.__origin__ is ClassVar
And after October 2024, when Python 3.8 reaches its end of life https://peps.python.org/pep-0569/, the number of lines will become even smaller.
There is another option using typing_extensions.get_origin
. This function use the native typing.get_origin
on Python >= 3.10 and has a workaround for older versions.
typing_extensions
from version 4.6.1 (up to 4.12.2 at least) has this function and this module is required by Pydantic >= 2.0 (up to 2.8.2 at least) so it's always installed with the Pydantic and available to use like this:
def is_classvar(tp):
return typing_extensions.get_origin(tp) is ClassVar
Describe the bug If I'm using Pydantic 2, cbv.py imports package
typing_inspect
. However this is listed as an optional dependency.To Reproduce Steps to reproduce the behavior:
fastapi dev ...
Expected behavior It doesn't crash
Screenshots
Environment:
0.3.0
], get them with:^ This also fails to run w/o typing_inspect.
After installing it:
3.11.6
Additional context Add any other context about the problem here.