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.)

It sounds like you want the "*" operator  for arguments:

  def foo(*args):
    print "Args:", repr(args)
    print " Type:", type(args)
    for i, arg in enumerate(args):
      print " Arg #%i = %s" % (i, arg)
  foo(1)
  foo("abc", "def", 42)
  # pass a list as args
  lst = [1,2,3]
  foo(*lst)

There's also a keyword form using "**":

  def foo(*args, **kwargs):
    print "Args:", repr(args)
    print " Type:", type(args)
    print "Keyword Args:", repr(kwargs)
    print " Type:", type(kwargs)
    for i, arg in enumerate(args):
      print " Arg #%i = %s" % (i+1, arg)
    for i, (k, v) in enumerate(kwargs.items()):
      print " kwarg #%i %r = %s" % (i+1, k, v)
  foo(1, "hello", something="Whatever", baz=42)
  # pass a list and a dict:
  lst = [1,2,3]
  dct = {100:10, 200:11}
  foo(*lst, **dct)

Both prevent introspection, so if you want the auto-generated help to populate with named arguments, you'd have to use the inspection method you're currently using. But generally, if you want to be able to treat the args as lists/tuples/dicts, you don't care about the names given.

-tim




--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to