2

In JavaScript each function has a special arguments predefined objects which holds information about arguments passed to the function call, e.g.

function test() {
  var args = Array.prototype.slice.call(arguments);
  console.log(args);
}

arguments can be easily dumped to a standard array:

test()
// []

test(1,2,3)
// [1, 2, 3]

test("hello", 123, {}, [], function(){})
// ["hello", 123, Object, Array[0], function]

I know that in Python I can use standard arguments, positional arguments and keyword arguments (just like defined here) to manage dynamic parameter number - but is there anything similar to arguments object in Python?

ducin
  • 25,621
  • 41
  • 157
  • 256
  • 1
    No. Like you said, the closest thing is varargs like `*args` and `**kwargs`, but those only give you "extra" arguments, not all arguments. There is somewhat less need for `arguments` in Python because (unlike Javascript) it's not possible to call a function with the wrong number of arguments (i.e., if a function requires two arguments, calling it with just one will give an error). What do you want to accomplish that makes you want to use something like `arguments`? – BrenBarn Jul 10 '13 at 22:06
  • @BrenBarn I was trying to implement all memoization techniques in python (basing on javascript patterns). In JS you make heavy use of `arguments`, e.g. you can make a standard `memoize` function with one parameter (which is a function to be memoized) which will return closured memoized function. This is done using `arguments`, as you can see [here](http://www.sitepoint.com/implementing-memoization-in-javascript/) (see chapter automatic memoization). – ducin Jul 10 '13 at 22:09
  • Instead of trying to copy JavaScript patterns, look around for examples of memoization in Python. In Python you can make a memoize decorator which can be used similarly to the sort of JS function you describe. Googling "Python memoize" will give you lots of ideas. – BrenBarn Jul 10 '13 at 22:11
  • Anyway, in Python there's nothing like `arguments`, as I can see. Thanks. – ducin Jul 10 '13 at 22:13
  • Fortunately, I found a duplicate of this question: [Get a list/tuple/dict of the arguments passed to a function?](http://stackoverflow.com/questions/2521901/get-a-list-tuple-dict-of-the-arguments-passed-to-a-function) – Anderson Green Jul 18 '13 at 23:01

1 Answers1

2

It doesnt exist as is in python but you can call locals() as the first thing in the function and at that point it should only have the arguments

>>> def f(a,b):
...    args = locals()
...    for arg, value in args.items():
...        print arg, value
...    return a*b
...
anijhaw
  • 8,954
  • 7
  • 35
  • 36
  • 1
    That is true, but if the function has varargs you'll just get them as a tuple/dict, not combined "flat" with the regular arguments. – BrenBarn Jul 10 '13 at 22:15