Instead of writing code like this every time I define a class:
class Foo(object):
def __init__(self, a, b, c, d, e, f, g):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
self.f = f
self.g = g
I could use this recipe for automatic attribute assignment.
class Foo(object):
@autoassign
def __init__(self, a, b, c, d, e, f, g):
pass
Two questions:
- Are there drawbacks or pitfalls associated with this shortcut?
- Is there a better way to achieve similar convenience?
There are some things about the autoassign code that bug me (mostly stylistic, but one more serious problem):
autoassigndoes not assign an‘args’ attribute:
autoassignacts like a decorator.But
autoassign(*argnames)calls afunction which returns a decorator.
To achieve this magic,
autoassignneeds to test the type of its first
argument. If given a choice, I
prefer functions not test
the type of its arguments.
There seems to be a considerable
amount of code devoted to setting up
sieve, lambdas within lambdas,ifilters, and lots of conditions.
I think there might be a simpler way. (See
below).
for _ in. I don’t thinkitertools.starmap(assigned.setdefault,
defaults): pass
maporstarmapwas meant to callfunctions, whose only purpose is their
side effects. It could have been
written more clearly with the mundane:
Here is an alternative simpler implementation which has the same functionality as autoassign (e.g. can do includes and excludes), and which addresses the above points:
And here is the unit test I used to check its behavior:
PS. Using
autoassignorautoargsis compatible with IPython code completion.