Skip to content

Commit 9812d9e

Browse files
committed
Compare the source code of lambda and local functions
1 parent 95d93bd commit 9812d9e

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

src/reactpy/core/hooks.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -518,11 +518,30 @@ def strictly_equal(x: Any, y: Any) -> bool:
518518
- ``bytearray``
519519
- ``memoryview``
520520
"""
521+
# Return early if the objects are not the same type
521522
if type(x) is not type(y):
522523
return False
523524

524-
with contextlib.suppress(Exception):
525-
if hasattr(x, "__eq__"):
525+
# Compare the source code of lambda and local functions
526+
if (
527+
hasattr(x, "__qualname__")
528+
and ("<lambda>" in x.__qualname__ or "<locals>" in x.__qualname__)
529+
and hasattr(x, "__code__")
530+
):
531+
if x.__qualname__ != y.__qualname__:
532+
return False
533+
534+
return all(
535+
getattr(x.__code__, attr) == getattr(y.__code__, attr)
536+
for attr in dir(x.__code__)
537+
if attr.startswith("co_")
538+
and attr not in {"co_positions", "co_linetable", "co_lines"}
539+
)
540+
541+
# Check via the `==` operator if possible
542+
if hasattr(x, "__eq__"):
543+
with contextlib.suppress(Exception):
526544
return x == y # type: ignore
527545

546+
# Fallback to identity check
528547
return x is y

tests/test_core/test_hooks.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1172,6 +1172,28 @@ def test_strictly_equal(x, y, result):
11721172
assert strictly_equal(x, y) is result
11731173

11741174

1175+
def test_strictly_equal_named_closures():
1176+
assert strictly_equal(lambda: "text", lambda: "text") is True
1177+
assert strictly_equal(lambda: "text", lambda: "not-text") is False
1178+
1179+
def x():
1180+
return "text"
1181+
1182+
def y():
1183+
return "not-text"
1184+
1185+
def generator():
1186+
def z():
1187+
return "text"
1188+
1189+
return z
1190+
1191+
assert strictly_equal(x, x) is True
1192+
assert strictly_equal(x, y) is False
1193+
assert strictly_equal(x, generator()) is False
1194+
assert strictly_equal(generator(), generator()) is True
1195+
1196+
11751197
STRICT_EQUALITY_VALUE_CONSTRUCTORS = [
11761198
lambda: "string-text",
11771199
lambda: b"byte-text",

0 commit comments

Comments
 (0)