2

Lets say we have this code..

def test(**test):
    print test
def test2(test):
    print test

test(test=1, asterisk=2)
t = {"test":1, "asterisk":2}
test2(t)

test and test2 function will print out the same result.

What are some benefits for using ** over passing a dictionary?

user3189106
  • 139
  • 1
  • 6
  • 1
    [check out the examples](http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-python-parameters/26365795#26365795) – LinkBerest Apr 16 '15 at 04:25
  • 1
    It's great syntactic sugar if you need functions to dynamically accept parameters or dynamically pass parameters. In "normal" code it may not be very obvious what this is good for, but in more dynamic or meta-programming code this is very useful. – deceze Apr 16 '15 at 04:27
  • If you are passing one parameter which happens to be a `dict` as in your question - don't use the `**` syntax - that's not what it's for. – John La Rooy Apr 16 '15 at 05:18

4 Answers4

5

If we take a look at your example:

test(test=1, asterisk=2)

is more readable than

t = {"test":1, "asterisk":2}
test2(t)

or

test2({"test":1, "asterisk":2})

So if you have a function that can accept a variable number of variably named arguments, that's the most readable way of doing it.

It works the other way too:

def add(a, b):
    return a + b
params = { "b": 5, "a": 6}
print(add(**params))

11

*args will give you a variable number of arguments:

def min(*args):
    min = None
    for v in args:
        if min is None or v < min:
            min = v
    return min

print(min(1, 7, 8, 9, 2, 1, 0))

0

This also works the other way:

def add(a, b):
    return a + b

t = [5, 6]
print(add(*t))

11

Both are used when wrapping other functions, like when creating function decorators:

def log_call(f):
    def logged(*args, **kwargs):
        print("Called {}".format(f.__name__))
        return f(*args, **kwargs)
    return logged

class A:
    @log_call
    def add_two_numbers(self):
        return 1 + 2

print(A().add_two_numbers())

Called add_two_numbers
3

Raniz
  • 10,882
  • 1
  • 32
  • 64
1

It's pretty essential when writing decorators. Ideally you want the decorator to work on functions with differing arguments.

def mydecorator(func):
    def new_func(*args, **kwargs):
        #do something here...
        return func(*args, **kwargs)
    return new_func
1.618
  • 1,765
  • 16
  • 26
0

used in Passing parameters with dict

let us consider a method

def foo(a=10,b=20):
   return a+b

Now you can pass parameters like this

d={'a'=20,'b'=30}

print foo(**d)

with ** Python dynamically pass the values to respective Parameters

output : 50

String Foramtting

coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
print 'Coordinates: {latitude}, {longitude}'.format(**coord)
output:'Coordinates: 37.24N, -115.81W'
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
-1

Basically, * returns value in tuple and ** returns in dictionary.