Skip to content

Commit

Permalink
tweaks: allow equal values with different names
Browse files Browse the repository at this point in the history
  • Loading branch information
CNSeniorious000 committed Apr 16, 2024
1 parent 1092483 commit e98adb1
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "literal-dict"
version = "1.0.1.1"
version = "1.1.0"
description = "Use JavaScript-like object definition syntax in Python"
authors = [{ name = "Muspi Merol", email = "me@muspimerol.site" }]
dependencies = []
Expand Down
10 changes: 7 additions & 3 deletions src/literal_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
class DictBuilder(Generic[D]):
def __init__(self, constructor: Callable[[dict], D] = dict):
self.constructor = constructor
assert callable(self.constructor), "Constructor must be callable"

def __getitem__(self, args: Union[slice, T, Sequence[Union[slice, T]]]) -> D:
if not isinstance(args, tuple):
Expand All @@ -26,18 +27,21 @@ def __getitem__(self, args: Union[slice, T, Sequence[Union[slice, T]]]) -> D:
obj[arg.start] = arg.stop
else:
for name, var in caller_frame.f_locals.items():
if var is arg:
if var is arg and name not in obj:
obj[name] = arg
break
else:
for name, var in caller_frame.f_globals.items():
if var is arg:
if var is arg and name not in obj:
obj[name] = arg
break
else:
for name, var in caller_frame.f_builtins.items():
if var is arg:
if var is arg and name not in obj:
obj[name] = arg
break

return self.constructor(obj) if self.constructor is not dict else obj # type: ignore

def __repr__(self):
return f"{self.__class__.__qualname__}({self.constructor.__qualname__})"
6 changes: 6 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,9 @@ def f():
assert d[print] == {"print": print}

f()


def test_same_value_different_name():
d = DictBuilder()
a = b = 1
assert d[a, b] == {"a": 1, "b": 1}

0 comments on commit e98adb1

Please sign in to comment.