You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Using types as defaults IMO makes the code more readable. Also assuming the callable takes no arguments, it allows simple initialization at run-time (like with datetime.now).
It's easy to do that with a simple sealer wrapper, like the one below:
fromfunctoolsimportwrapsfromfieldsimportfactory, tuple_sealerdefwith_callable_defaults(sealer):
""" Wraps the given `sealer` to support `callable` for any specified default. """@wraps(sealer)defwrapped_sealer(fields, defaults):
forfield, defaultindefaults.iteritems():
ifcallable(default):
try:
defaults[field] =default()
exceptTypeError:
passreturnsealer(fields, defaults)
returnwrapped_sealerTuple=factory(with_callable_defaults(tuple_sealer))
I was thinking of abusing the slice syntax at first :) Could be useful for things like validators, converters, or even docstrings, esp. if combined with your suggestion about supporting strings:
Well yes, fields is not meant to replace attrs, or even compete with it. As a matter of fact it precedes attrs (it's practically a jab at characteristic). You may have guessed it, attrs probably wouldn't exist if I hadn't done fields xD
Intended use is very small classes (5 fields or less). If you can't fit it on one line then probably you shouldn't use fields at all - the whole idea of extreme brevity become a moot point if you split the definition on multiple lines in ugly jquery chain style.
Activity
ionelmc commentedon May 15, 2017
Another way, that can also keep backwards compat a bit is to (ab)use slices for defaults as callables, eg:
or even with strings for more possibilities (the init function is made from a string, alike namedtuple, so this is possible):
ionelmc commentedon May 15, 2017
Actually both forms could be supported.
Anyway, doesn't
attrsalready support default values from callables?dimitern commentedon May 16, 2017
I was thinking of abusing the slice syntax at first :) Could be useful for things like validators, converters, or even docstrings, esp. if combined with your suggestion about supporting strings:
Yeah,
attrssupports callable defaults and lots more, but I like the concise declarative style offieldsbetter I think :)I'll look into it some more, cheers!
ionelmc commentedon May 16, 2017
Well yes,
fieldsis not meant to replaceattrs, or even compete with it. As a matter of fact it precedesattrs(it's practically a jab at characteristic). You may have guessed it,attrsprobably wouldn't exist if I hadn't donefieldsxDIntended use is very small classes (5 fields or less). If you can't fit it on one line then probably you shouldn't use
fieldsat all - the whole idea of extreme brevity become a moot point if you split the definition on multiple lines in ugly jquery chain style.