How to access args as a list?

MRAB python at
Sat Apr 3 19:20:52 EDT 2010

kj wrote:
> Suppose I have a function with the following signature:
> def spam(x, y, z):
>     # etc.
> Is there a way to refer, within the function, to all its arguments
> as a single list?  (I.e. I'm looking for Python's equivalent of
> Perl's @_ variable.)
> I'm aware of locals(), but I want to preserve the order in which
> the arguments appear in the signature.
> My immediate aim is to set up a simple class that will allow me to
> iterate over the arguments passed to the constructor (plus let me
> refer to these individual arguments by their names using an
> instance.attribute syntax, as usual).
> The best I have managed looks like this:
> class _Spam(object):
>     def __init__(self, x, y, z): 
>         self.__dict__ = OrderedDict(())
>         for p in inspect.getargspec(_Spam.__init__).args[1:]:
>             self.__dict__[p] = locals()[p]
>     def __iter__(self):
>         return iter(self.__dict__.values())
> but rolling out inspect.getargspec for this sort of thing looks to
> me like overkill.  Is there a more basic approach?
> P.S. this is just an example; the function I want to implement has
> more parameters in its signature, with longer, more informative
> names.
I think the closest approach to what you're asking is to capture the
arguments as a list and then bind them to local names:

     def spam(*args):
         x, y, z = args
         # etc.

More information about the Python-list mailing list