我有这种类型:
class SomeResource:
id: int
name: str
我需要这种类型:
class SomeResourceQuery:
id: Optional[int]
name: Optional[str]
但我想避免手写.是否可以从SomeResource
类型生成此SomeResourceQuery
类型?只需将所有类型的字段转换为可选字段.(更新:已经可选的字段可以保持可选-没有嵌套的选项.)
我计划在存储库中使用这SomeResourceQuery
,如下所示:
class SomeResourceRepository:
def get_one_or_none(self, query: SomeResourceQuery) -> Optional[SomeResource]:
...
更新:只是为了展示我目前的 idea :
class SomeResource:
id: int
name: str
# I don't want to write this by hand:
# class SomeResourceQuery:
# id: Optional[int]
# name: Optional[str]
# So what can I do here to make all fields that are not already optional, optional?
SomeResourceQuery = type("SomeResourceQuery", SomeResource) # What to do here?