by runarberg · 8y ago · 0 comments
An interesting observation is that while python has separate operators for lists ( * ) and dictionaries ( * * )—javascript has only `...`.
> You need to be careful when using multiple times though. Functions in Python can’t have the same keyword argument specified multiple times, so the keys in each dictionary used with must be distinct or an exception will be raised.
This is not an issue in javascript, the unpacked object with repeated keys takes the value of the last one.
{...{a: 1}, ...{a: 2}}
// => {a: 2}
edit: formattingIn JavaScript, the surrounding syntatical context solely decides if it's an object or array splat. But since Python has 2 kinds of parameters, to preserve obviousness when reading code using splats, they went with 2 operators for each parameter kind, and then separated list and dictionary splat analogously.
The other reason to distinguish * and double-* is because * works with any iterable, and dicts are themselves iterables (of their keys). So you can actually use * on dicts, it just does something different:
>>> d = {'a': 1, 'b' : 2}
>>> [*d]
['a', 'b']
You could arguably say that only * makes sense here since it's a list context. But then, as you say, function calls would still be ambiguous because they support both positional and named arguments. This keeps it all unambiguously consistent in all contexts.>>> {{'a': 1}, {'a': 2}} {'a': 2}
So the multiple keyword argument problem isn't an inherent issue with so much as it's a problem with keyword arguments being specified twice (which has been a restriction since before they allowed multiple to be used).
A := []int{1,2}
B := append(A, A...)
fmt.Println(B)
> [1, 2, 1, 2]