3 ms·
I just started learning Python, what does this syntax mean? **json.loads(my_json)) from with_slots = [get_size(MyUserWithSlots(**json.loads(my_json))
by spraak 9y ago
I just started learning Python, what does this syntax mean?
**json.loads(my_json))
from
with_slots = [get_size(MyUserWithSlots(**json.loads(my_json))) for _ in range(NUM_INSTANCES)]
Edit: I mean, I get what it's doing, but specifically I don't understand the double * (somehow it's not rendering in this comment)
- vtbassmatt 9y agoThis uses the key-value pairs as keyword arguments.
- jedberg 9y agoUnpacks the object into a dictionary. It's syntactic sugar: https://stackoverflow.com/a/2921893/66202 https://stackoverflow.com/a/2921893/66202
- deathanatos 9y agoA function in Python takes two kinds of arguments: positional arguments, and keyword arguments. def foo(a, b, c): pass # Arguments passed positionally: foo(1, 2, 3) # or passed by keyword: foo(a=1, b=2, c=3) Now, say you want to make that second call somewhat dynamically, and you have the dict: a_dict = {'a': 1, 'b': 2, 'c': 3} You can make that second foo call: foo(**a_dict) # because of the value of a_dict, expands to: # foo(a=1, b=2, c=3) Functions themselves can take only positional arguments, only keyword arguments, or really, any combination of them. Here is a decent SO question and answer[1] that might help, a bit about it in the tutorial[2], and last, the formal documentation[3]. [1]: https://stackoverflow.com/questions/1419046/python-normal-arguments-vs-keyword-arguments https://stackoverflow.com/questions/1419046/python-normal-ar... [2]: https://docs.python.org/2/tutorial/controlflow.html#keyword-arguments https://docs.python.org/2/tutorial/controlflow.html#keyword-... [3]: https://docs.python.org/2/reference/expressions.html#grammar-token-call https://docs.python.org/2/reference/expressions.html#grammar...
- spraak 9y agoAwesome, thank you for the detailed explanation!