Monday, August 6, 2012

How to use *args and **kwargs in Python

from
http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

http://docs.python.org/tutorial/controlflow.html#keyword-arguments


def test_var_args(farg, *args):
    print "formal arg:",farg
    for arg in args:
        print  "another arg:",arg
  


def test_var_kwargs(farg, **kwargs):
    print "formal arg:",farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

test_var_args(1, "two", 3, "four")
print '-'*40
test_var_kwargs(farg = 1, myarg2 = "two", myarg3 = 3, myarg4 = "four")


def test_var_args_call(arg1, arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "arg3:", arg3

args = ("two", 3)
test_var_args_call(1, *args)


def test_var_args_call(arg1, arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "arg3:", arg3

kwargs = {"arg3": 3, "arg2": "two"}
test_var_args_call(1, **kwargs)

No comments: