-
Notifications
You must be signed in to change notification settings - Fork 63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add on_set / on_get callbacks to fields #57
Comments
Do you think the new marshmallow's pre/post processors integration (see #60 (comment)) could be used as a workaround for this ? |
Not sure. The class User(Document):
birthday = DateTimeField(on_set=self._compute_age) # either here
age = IntField()
def _compute_age(self):
self.age = (datetime.utcnow() - self.birthday).days / 365 # Who cares about precision?
chuck = User()
chuck.age = None
chuck.birthday = datetime.datetime(year=1940, month=3, day=10)
chuck.age = 76 I don't think you can do this with |
You're right, marshmallow's pre/post processors is not the silver bullet we were waiting for ! I'm thinking of a new way to implement this feature:
example: >>> def capitalize(value):
... print('capitalize !')
... return value.to_upper()
...
>>> def double(value):
... print('double !')
... return value + ' ' + value
...
>>> class User(Document):
... name = fields.StrField(on_get=[capitalize, double])
... lastname = fields.StrField(on_set=[capitalize, double])
...
>>> user = User(name='john', lastname='doe')
capitalize !
double !
>>> user.lastname
'DOE DOE'
>>> user.name
capitalize !
double !
'JOHN JOHN'
>>> lazy_obj = user._data._data['name']
>>> lazy_obj
<LazyObj(fn=double, value=LazyObj(fn=capitalize, value='john'))>
>>> lazy_obj.eval()
capitalize !
double !
'JOHN JOHN' But I'm still unsure how useful it would be for Usecase for |
I also see more use for
And Questions:
|
Following discussing here.
I wrote:
@touilleMan answered:
I didn't think about the
update
use case. It seems this feature is more complicated than I expected.I'd like to add a new requirement.
on_[g|s]et
should be lists of callbacks rather than callbacks, to allow several callbacks to be set, with a deterministic order.The text was updated successfully, but these errors were encountered: