Python - Iterating over Arguments passed to a Function
<p>Suppose I have the following example:</p>

<pre><code>class foo:
   ...
   def bar(self, w, x, y, z, ...):
      self.w = w
      self.x = x
      self.y = y
      self.z = z
      ...
</code></pre>

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

<p>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 <a href="http://stackoverflow.com/questions/739654/how-to-make-a-chain-of-function-decorators-in-python/1594484#1594484">functions can be handled like objects</a>; so is it possible to obtain a list of the defined parameters as an attribute of the function and iterate through that?</p>

<p>Use <code>locals()</code> and you can get all the arguments (and any other local variables):</p>

<pre><code>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)
        ...
</code></pre>

<p>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.</p>

python arguments variable-assignment setattr