S. Gamgee S. Gamgee - 11 months ago 55
Python Question

Python - Iterating over Arguments passed to a Function

Suppose I have the following example:

class foo:
...
def bar(self, w, x, y, z, ...):
self.w = w
self.x = x
self.y = y
self.z = z
...


I wish to reduce the n-number of attribute assignment lines in
bar()
to one assignment line set using a
setattr()
cycle through the arguments. Is there a good way to cycle through said arguments for this purpose?

I wish to retain the defined parameter names so as to limit the number of parameters passed to the function as well as the order in which they are passed. I also understand that functions can be handled like objects; so is it possible to obtain a list of the defined parameters as an attribute of the function and iterate through that?

Answer Source

Use locals() and you can get all the arguments (and any other local variables):

class foo:
    def bar(self, w, x, y, z):
        argdict = {arg: locals()[arg] for arg in ('w', 'x', 'y', 'z')}
        for key, value in argdict.iteritems():
            setattr(self, key, value)
        ...

Might be possible to do it more efficiently, and you could inline argdict if you prefer less lines to readability or find it more readable that way.