other-languages

grav 2024-01-30T11:11:30.882889Z

Is there something akin to destructuring maps (dicts) in Python? Like (let [{:keys [foo bar]} {:foo 42 :bar "hello"}] ...)

Ben Sless 2024-01-30T12:50:55.596469Z

foo(**a_dict) destrcutures the dict and can pass it to a function with named arguments

grav 2024-01-30T12:51:48.886289Z

nice - any reference you can point at? (not sure what to google 😅)

mauricio.szabo 2024-01-30T12:52:12.449689Z

Splat operator?

grav 2024-01-30T12:52:37.973029Z

great, thanks!

Ben Sless 2024-01-30T12:55:30.489439Z

python kwargs

2024-01-30T13:02:20.169219Z

if it is about picking data from a Python dict, I usually do something like this, a comprehension:

{k: v for k, v in data.items() if k in {"foo", "bar"}}
(also, could be put in a pick function, accepting a dict and a set of keys)
def pick(data: dict, keys: set) -> dict:
    return {k: v for k, v in data.items() if k in keys}
or, the opposite 😄
def omit(data: dict, keys: set) -> dict:
    return {k: v for k, v in data.items() if k not in keys}

2024-01-30T13:09:38.425509Z

If it's the values only, you can return {v (the return type will be a set )

teodorlu 2024-01-30T18:05:07.300149Z

an example of @ben.sless’s suggestion, without a named function:

>>> (lambda x, y: print("x=", x, "y=", y))(**{"x": 10, "y": 20})
x= 10 y= 20
so it could be used with a lambda instead of a named function — but readability may suffer. You could return a tuple from the function and bind to that,
>>> x, y = (lambda x, y: (x, y))(**{"x": 10, "y": 20})
>>> x, y
(10, 20)
Still skeptical about readability. Yet another attempt:
>>> d = {"x": 10, "y": 20}
>>> splat = lambda s, d: [d[x] for x in s.split()]
>>> x, y = splat("x y", d)
>>> x, y
(10, 20)
still skeptical about readability. You be the judge 🙂

Ben Sless 2024-01-30T18:31:04.358919Z

I have a lot to judge Python for, think I'll pass

😅 2