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
you end up writing 9 times param, for each attribute you add. I love python, and things being explicit better than implicit, but we're light years away from DRY here. This is being…
I suggest instead to use some tricks like, the attrs module:
But we can make it totally DRY, the following way:
importattr@attr.sclassGogsEntity:
json=attr.ib()
@classmethoddeffrom_json(cls, parsed_json):
# with introspection, get arguments of the constructorparams=attr.fields(cls)
args= []
kwargs= {}
forparaminparams:
# if not a keyword argumentifparam.name==attr._make._Nothing:
args.append(json_get(parsed_json, param.name))
# if it's a keyword argumentelse:
kwargs[param.name] =parsed_json.get(param.name, None)
delkwargs['json']
instance=cls(*args, json=parsed_json, **kwargs)
returninstance@attr.s(frozen=True)classGogsFoobar(GogsEntity):
foo=attr.ib()
foobar=attr.ib(default=42)
x=GogsFoobar.from_json(dict(foo=1, foobar=2))
print(x.foo, x.foobar, x.json)
and now you only write the attribute once. But I agree, it's using some creepy dirty internal automagic from python. At the cost of making it uglier in one place, you make it DRY everywhere else, with the same strong type checkings you enforce currently.
The text was updated successfully, but these errors were encountered:
Uh oh!
There was an error while loading. Please reload this page.
The code relies a lot on a common super-verbose pattern:
you end up writing 9 times
param
, for each attribute you add. I love python, and things being explicit better than implicit, but we're light years away from DRY here. This is being…I suggest instead to use some tricks like, the
attrs
module:it's now down to 4.
But we can make it totally DRY, the following way:
and now you only write the attribute once. But I agree, it's using some creepy dirty internal automagic from python. At the cost of making it uglier in one place, you make it DRY everywhere else, with the same strong type checkings you enforce currently.
The text was updated successfully, but these errors were encountered: