schema icon indicating copy to clipboard operation
schema copied to clipboard

Suggestion or Issue? default= with a function/lambda

Open mianos opened this issue 8 years ago • 6 comments
trafficstars

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?

mianos avatar May 11 '17 00:05 mianos

Write a function that accepts the value and returns the default if the value is None and Use() it?

skorokithakis avatar May 11 '17 00:05 skorokithakis

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.

mianos avatar May 11 '17 00:05 mianos

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.

skorokithakis avatar May 11 '17 00:05 skorokithakis

OK, if you are interested I'll add the code and send you a pull request in the next few days. :)

mianos avatar May 11 '17 00:05 mianos

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 avatar May 24 '17 01:05 kurtbrose

@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.

skorokithakis avatar May 24 '17 13:05 skorokithakis