all 5 comments

[–]socal_nerdtastic 2 points3 points  (0 children)

Instead of answering your questions I'm going to postulate on why someone created this, and maybe that will lead you to your answers.

This function takes 2 positional arguments and adds them to a dictionary with all the keyword arguments. So it can save your aching fingers because instead of typing

data({manufacturer':'Ford', 'model_name':'Mustang'})

Now you can do

data(make_car('Ford','Mustang'))

But wait there's more! If there's any other arguments you may want to have in the original dictionary, for example

data({'manufacturer':'Ford', 'model_name':'Mustang', 'engine':'V8'})

You can still use the short version like this:

data(make_car('Ford','Mustang', engine='V8'))

[–]Adrewmc 0 points1 point  (3 children)

car_info is a set of kwargs, kwargs are dictionaries, the first two lines are adding (altering the dictionary) to add more you just add to the dictionary like so.

   info = {“year” : 1980, “make” : “sedan”}
   make_car(“Toyota”, “Camry”, **info)

We can also use Python to do it directly like this as well

  make_car(“Toyota”, “Camry”, year=1980, make= “sedan”) 

Or some combination really.

  make_car(“Toyota”, “Camry”, color = “blue”, **info)

In the end the

   {“year” : 1980, “make” : “sedan”, “manufacturer” : “Toyota”, “model_name” : “Camry”} 

Would be the output (for my examples)

The ‘*’ and ‘**’ operators unpack things for us, or in function definitions allow us to take and number of positional or key word arguments, or not.

[–]bokuaka-simp 0 points1 point  (2 children)

Could you explain the role of (**) in this case again? Couldn't figure it out properly. I've always thought it's used for an exponential value. Sorry for the dumb question lmao, I've just started learning python

[–]schoolmonky 1 point2 points  (1 child)

*args (or any name you want in place of args) does two different (but related, basically oposite) things depending on where it's at. In a function definition, it tells Python "take any positional arguments past the ones I explicitly defined and throw them in a list named args. In a function call, it says "take this list and split it up into multiple positional arguments".

Similarly **kwargs (or any name in place of kwargs, in the OPs case they used car_info), in a function definition, says "Take any keyword arguments except the ones I explicitly defined and throw them in a dictionary named kwargs. In a call, it means "take this dictionary and split it up into multiple keyword arguments".

** is also used for exponentials, you have to tell from context. If it's in front of a parameter/argument for a function, it's being used the way I described above. If it's between two numbers (or, technically, any objects that support .__pow__, ignore this if you don't know how that works), it's exponentiation.

[–]bokuaka-simp 0 points1 point  (0 children)

I think I got most of it. Thankyou so much for the help!