Is it appropriate to implement a poly model using validate func?
See original GitHub issuesample code:
from enum import IntEnum
from pydantic import BaseModel
class FooTypeEnum(IntEnum):
A = 1
B = 2
class Foo(BaseModel):
type: int
@classmethod
def validate(cls, value):
type_to_model = {
FooTypeEnum.A: FooA,
FooTypeEnum.B: FooB,
None: cls
}
_type = value.get('type', None)
try:
return type_to_model[_type](**value)
except KeyError:
raise TypeError(f'no model for type: {_type}')
class FooA(Foo):
a: str
class FooB(Foo):
b: str
class Bar(BaseModel):
foo: Foo = ...
m = Bar(foo={'type': FooTypeEnum.A, 'a': 'aaa'})
print(m)
# Bar foo=<FooA type=1 a='aaa'>
print(m.dict())
# {'foo': {'type': 1, 'a': 'aaa'}}
m = Bar(foo={'type': FooTypeEnum.B, 'b': 'bbb'})
print(m)
# Bar foo=<FooB type=2 b='bbb'>
print(m.dict())
# {'foo': {'type': 2, 'b': 'bbb'}}
# m = Bar(foo={'type': FooTypeEnum.B, 'c': 'bbb'})
# error ...
# m = Bar(foo={'type': 3, 'c': 'bbb'})
# error ...
# m = Bar(foo={'c': 'bbb'})
# error ...
Issue Analytics
- State:
- Created 6 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Is it appropriate to implement a poly model using validate func?
A: FooA, FooTypeEnum.B: FooB, None: cls } _type = value.get('type', None) try: return type_to_model[_type](**value) except KeyError: raise ...
Read more >Lab 12 - Polynomial Regression and Step Functions in R
We first fit the polynomial regression model using the following command: ... the appropriate response vector, and then apply the glm() function using...
Read more >Python | Implementation of Polynomial Regression
Polynomial Regression is a form of linear regression in which the relationship between the independent variable x and dependent variable y ...
Read more >Training-validation-test split and cross-validation done right
In this tutorial, you will discover the correct procedure to use cross validation and a dataset to select the best models for a...
Read more >Lab 2 - andrew.cmu.ed
Describe what the sample() function as used above actually does. ... (e) Use the poly() command to fit a quadratic regression model of...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
no problem, glad it helped.
Looks like you just need to use
Union
:Pydantic tries each of the different types in Union to see if they’re valid and returns the first which is.