Skip to content

Instantly share code, notes, and snippets.

@SimonHauguel
Created August 11, 2023 15:31
Show Gist options
  • Save SimonHauguel/6cab41f5eb1651dce151d5d0710e3927 to your computer and use it in GitHub Desktop.
Save SimonHauguel/6cab41f5eb1651dce151d5d0710e3927 to your computer and use it in GitHub Desktop.
(JS destructuring assignment)-like in Python
# It "works"
from __future__ import annotations
import operator
@lambda x: x() # Since 3.10, maybe ? Works at least in 3.11
class __annotations__:
def __setitem__(self, key, value):
command,target = value.replace(" ", "").split("@")
if command == "UNPACK":
getter_keys = key.split("_")
result_itemgetter = operator.itemgetter(*getter_keys)(globals()[target])
# We can easily handle default values, non existing key, rest, ...
# Simply loop over getter_keys
globals().update(zip(getter_keys, result_itemgetter))
my_dict = { "foo" : "Hello", "bar" : "World!", "ignore" : "Black Magic 🧙‍♂️" }
foo_bar : UNPACK@my_dict
print(foo, bar) # Hello World!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment