schema icon indicating copy to clipboard operation
schema copied to clipboard

Add "default_factory" to Optional and always take "default" as it is

Open JasonXJ opened this issue 6 years ago • 2 comments

Recent commit https://github.com/keleshev/schema/commit/b73fb7187da46b627d84460bc981f45a28a438de treats callable default param to Optional specially (i.e. calling it instead of using it as it is)

This can cause confusion --- what if I want a callable itself as the default? For example, I might have this schema:

Schema({Optional('key_type', default=str): type})

And the after this commit I am going to get {'key_type': ''} instead of {'key_type': str} if key_type is missing.

I would suggest reverting this asap before the new behavior is widely used and add default_factory for the same purpose, which is just what stdlib dataclasses.field and collections.defaultdict do

JasonXJ avatar Mar 06 '19 06:03 JasonXJ

Hmm, the current behaviour seems the least surprising to me. However, I can see how people might be surprised by specifying a default and having it called instead of passed, unexpectedly.

The question is, what do people do usually? Would someone pass a callable in default and not expect it to be called by Optional? I think no, but I'm open to other opinions.

Your proposal makes sense as an alternative, if we decide to change this.

skorokithakis avatar Mar 07 '19 14:03 skorokithakis

i agree with mirroring dataclasses behavior with default and default_factory

igor47 avatar Mar 29 '19 20:03 igor47