here is a small portion of code
import networkx as nx
G=nx.MultiDiGraph()
...
G.add_edge(white, black, **game)
(game is a dictionnary) what is the role of ** in the last line
here is a small portion of code
import networkx as nx
G=nx.MultiDiGraph()
...
G.add_edge(white, black, **game)
(game is a dictionnary) what is the role of ** in the last line
**
is the operator which unpacks mapping types (e.g. a dict
) into keyword arguments.
Consider:
def foo(bar=1):
print bar
d = {'bar':2}
foo(**d)
In this example, 2
will be printed. On the other side, you can also absorb all unknown keyword arguments in a **kwargs
type variable:
def foo(a=1,b=2,**kwargs):
print kwargs
foo(a=1,b=2,c=3)
Of course, you can combine these forms as well:
def foo(a=1,b=2,**kwargs):
print b
print kwargs
d = {'b':3, 'c':4}
foo(**d)
The function add_edge
gets passed in the dictionary game
as keyword arguments. For example, the following two are equivalent:
game = {'weight': 5, 'color': 'blue'}
G.add_edge(white, black, **game)
G.add_edge(white, black, weight=5, color='blue')
It expands a dictionary so its key-pair values are used as named parameters. Consider, for example, this function:
>>> def f(a, b, c):
... return a+b-c
...
I can call it passing its arguments in the original order:
>>> f(1,2,3)
0
But I can also switch them if I attribute values to the argument names:
>>> f(1,c=3,b=2)
0
When one calls a function passing a dictionary preceded by **
, the pairs of this dictionary will be used as parameters. So, I could create the dictionary below
>>> params = {'c':3, 'b':2}
...and pass it to my function...
>>> f(1,**params)
0
...and will get the same result.
It means that the argument is a dictionary, basically.
It's usually used as **kwargs
, meaning, keyword arguments.
For instance, when you define a method like:
def myMethod(first, *args, **kwargs):
....
It means that the second argument is expected to be a collection (a "list" of arguments), and kwargs
is meant to be a dict
.