I need my model to accept either a bytes type variable or a string type variable and to raise an exception if any other type was passed.
from typing import Union
from pydantic import BaseModel
class MyModel(BaseModel):
a: Union[bytes, str]
m1 = MyModel(a='123')
m2 = MyModel(a=b'123')
print(type(m1.a))
print(type(m2.a))
In my case the model interprets both bytes and string as bytes.
Output:
<class 'bytes'>
<class 'bytes'>
Desired output:
<class 'str'>
<class 'bytes'>
The desired output above can be achieved if I re-assign member a:
m1 = MyModel(a='123')
m1.a = '123'
Is it possible to get it in one go?