File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change 1010 ClassVar ,
1111 Protocol ,
1212 Required ,
13+ ParamSpec ,
1314 TypedDict ,
1415 TypeGuard ,
1516 final ,
6768__all__ = ["BaseModel" , "GenericModel" ]
6869
6970_T = TypeVar ("_T" )
71+ _BaseModelT = TypeVar ("_BaseModelT" , bound = "BaseModel" )
72+
73+ P = ParamSpec ("P" )
7074
7175
7276@runtime_checkable
@@ -379,6 +383,29 @@ def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericMo
379383 return issubclass (origin , BaseModel ) or issubclass (origin , GenericModel )
380384
381385
386+ def build (
387+ base_model_cls : Callable [P , _BaseModelT ],
388+ * args : P .args ,
389+ ** kwargs : P .kwargs ,
390+ ) -> _BaseModelT :
391+ """Construct a BaseModel class without validation.
392+
393+ This is useful for cases where you need to instantiate a `BaseModel`
394+ from an API response as this provides type-safe params which isn't supported
395+ by helpers like `construct_type()`.
396+
397+ ```py
398+ build(MyModel, my_field_a="foo", my_field_b=123)
399+ ```
400+ """
401+ if args :
402+ raise TypeError (
403+ "Received positional arguments which are not supported; Keyword arguments must be used instead" ,
404+ )
405+
406+ return cast (_BaseModelT , construct_type (type_ = base_model_cls , value = kwargs ))
407+
408+
382409def construct_type (* , value : object , type_ : object ) -> object :
383410 """Loose coercion to the expected type with construction of nested values.
384411
You can’t perform that action at this time.
0 commit comments