0

Possibly i know the following uses of **

Power

x ** y # x power y equivalent to pow(x,y)

Passing indefinite number of args

def sample(x, **other):
    print(x, other.keys)
sample(x=2,y=3,z=4) 

But i don't understand when its used as follow( in Serializers)

def create(self, validated_data):
    return Comment(**validated_data)

Can someone give me a hint of what is happening there

Emmanuel Mtali
  • 4,383
  • 3
  • 27
  • 53

1 Answers1

4

It is the opposite of your second example. When in the definition of a function, the ** operator gathers all the named arguments and makes a dictionary. When calling a function, it takes a dictionary and breaks it into named arguments

So, if you have

values = {'x': 1, 'y': 2}
f(**values)

it is the equivalent of

f(x=1, y=2)
blue_note
  • 27,712
  • 9
  • 72
  • 90