目录
前言
在写项目的时候,我实现了一个泛型容器,希望能够用来兼容多个实体的shema。但是这时候出问题了,我发现通过Generic容器传入的schema参数并没有什么用?
这是为什么呢?
原因就在于:泛型只是一个hint,可以帮助提示你应该输入什么类型的参数以及可以提示ID E此处应该传入什么参数,从而提醒你是否出错的参数。但是泛型(包括typing里的所有变量)并无法帮助你完成schema的功能。所以,我当初就是没有意识到这一点,才傻傻的去实现,结果没有任何作用,但是我又找到一种方法,可以拿到Generic容器中的类。
一、证明Generic无法shema
我们这里看一个简单的程序,然后最后我会贴出我项目中遇到的问题,并且是怎样解决的。
from typing import TypeVar, Type
T = TypeVar('T')
class Test(Generic[T]):
def hello(self):
my_type = T # this is wrong!
print( "I am {0}".format(my_type) )
Test[int]().hello()
# should print "I am int"
# however, it prints "I am ~T"
上面代码输出了 "I am ~T",很意外。
下面代码会证明它无法schema
from typing import Generic, TypeVar
from pydantic import BaseModel
class ModelSchema(BaseModel):
name: str
age: int
Model = TypeVar("Model", bound=BaseModel)
class CRUDBase(Generic[Model]):
def print_type(a: Model):
print(a)
print(type(a))
class Service1(CRUDBase[ModelSchema]):
pass
Service1.print_type(18)
如果schema管用的话,Service1.print_type(