Created
August 11, 2023 15:31
-
-
Save SimonHauguel/6cab41f5eb1651dce151d5d0710e3927 to your computer and use it in GitHub Desktop.
(JS destructuring assignment)-like in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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