2

I am scratching my head on what is going in the following code.

class foo(object):
    def __init__(self,*args):
        print type(args)
        print args

j_dict = {'rmaNumber':1111, 'caseNo':2222} 
print type(j_dict)
p = foo(j_dict)

it yields :

<type 'dict'>
<type 'tuple'>
({'rmaNumber': 1111, 'caseNo': 2222},)

It seems to me that this code converts a dict to a tuple!! Can anyone explain this

nitin
  • 7,234
  • 11
  • 39
  • 53

2 Answers2

8

Actually it's because args is a tuple to hold a variable length argument list. args[0] is still your dict - no conversion has taken place.

See this tutorial for further information about args and kwargs (the keyword version of args).

jmetz
  • 12,144
  • 3
  • 30
  • 41
3

When you use *args, all the positional arguments are "zipped" or "packed" in a tuple.

I you use **kwargs, all the keyword arguments are packed into a dictionary.

(Actually the names args or kwargs are irrelevant, what matters are the asterisks) :-)

For example:

>>> def hello(* args):
...     print "Type of args (gonna be tuple): %s, args: %s" % (type(args), args)
... 
>>> hello("foo", "bar", "baz")
Type of args (gonna be tuple): <type 'tuple'>, args: ('foo', 'bar', 'baz')

Now, this wouldn't happen if you didn't "pack" those args.

>>> def hello(arg1, arg2, arg3):
...     print "Type of arg1: %s, arg1: %s" % (type(arg1), arg1)
...     print "Type of arg2: %s, arg2: %s" % (type(arg2), arg2)
...     print "Type of arg3: %s, arg3: %s" % (type(arg3), arg3)
... 
>>> hello("foo", "bar", "baz")
Type of arg1: <type 'str'>, arg1: foo
Type of arg2: <type 'str'>, arg2: bar
Type of arg3: <type 'str'>, arg3: baz

You can also refer to this question Python method/function arguments starting with asterisk and dual asterisk

Community
  • 1
  • 1
Savir
  • 17,568
  • 15
  • 82
  • 136