from pydantic import BaseModel, field_validator
class Test(BaseModel):
x: int = 1
@field_validator('x')
def convert_to_int(cls, value):
return int(value) # Convert incoming value to int
# Usage
test = Test(x="3")
print(test.x) # Output: 3
Using param:
import param
class Test(param.Parameterized):
x = param.Number(default=1, bounds=(0, 10))
@param.depends("x", watch=True)
def _update_x(self):
self.x = int(self.x)
test = Test()
test.x = "3"
I get:
ValueError: Number parameter 'Test.x' only takes numeric values, not <class 'str'>.
I believe you’d have to create a custom parameter, inheriting from param.Number or param.Parameter, then implement your own __set__ and _validate methods.
Easier with param.Number, imo as you just super() the original set and validation logic from param.Number after you handle the conversion.