schema
schema copied to clipboard
Suggestion or Issue? default= with a function/lambda
I have used schema in a lot of places over the last few years and I only just had this need. I wanted to set a default value if the item is not present but I wanted to get the value from the configuration store (zookeeper). It would be good to be able to use:
..
Optional('max_invoices_to_process', default=lambda: g.zk.get('max_invoices_to_process', 1): Use(int),
..
This does not work yet as the default is a literal assignment. Thoughts anyone?
Write a function that accepts the value and returns the default if the value is None and Use() it?
Yes, this is what I did already:
Optional('max_invoices_to_process', default=None): Use(lambda vv: g.zk.get('max_invoices_to_process', 0) if not vv else int(vv)))
Works but is not as literal. I like my schema blocks to communicate 'intent' without using procedure. No real problem.
You aren't wrong, and I would be favorable towards a PR that accepted a function as a default, if you would like to give it a shot.
OK, if you are interested I'll add the code and send you a pull request in the next few days. :)
Another much less obscure use case comes to mind: if you want your default to be a dict or list but don't want multiple validate() calls to return the same instance.
Same issue as mutable function defaults def foo(a={}).
Being able to do schema.Optional(.., default=lambda: {}) would be great for that.
@kurtbrose: Good call, agreed.
I also wonder whether the function should accept arguments (e.g. the object being validated), so the default can depend on the validated object or something similar.