"ES6-like" Python dict spread

not very pretty, but you can sort of get there doing:

def f1(a, b, c, **_):
    print(a)
    print(b)
    print(c)

d = {"a": 1, "b": 2, "c": 3}

f1(**d)

very different semantics, but posted in the hope it'll inspire something!

as per @phhu's comment, ** in the definition of f1 is a catch-all keyword argument specifier telling Python that all unmatched parameters should be put into a dictionary of the given name, _ in my case. calling as f1(**d) says to unpack the specified dictionary into the function's parameters.

hence if it was used like:

e = {"a": 1, "b": 2, "c": 3, "extra": 42}

f1(**e)

then inside f1 the _ variable would be set to {"extra": 42}. I'm using _ because this identifier is used across a few languages to indicate a throwaway/placeholder variable name, i.e. something that is not expected to be used later.


No this isn't really possible. You can't have

a, b, c = spread(d)

and

a, c, b = spread(d)

give the same value to b. This is because the right side of an assignment statement is evaluated first. So spread executes and returns its values before your code knows which order you put them in on the left.

Some googling leads be to believe that by "spread-like syntax for dicts", you're looking for the **dict syntax. See What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

Tags:

Python