Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up __eq__ #1310

Merged
merged 6 commits into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1310.change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Speed up the generated `__eq__` methods significantly.
hynek marked this conversation as resolved.
Show resolved Hide resolved
14 changes: 7 additions & 7 deletions src/attr/_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -1864,20 +1864,20 @@ def _make_eq(cls, attrs):
globs = {}
if attrs:
lines.append(" return (")
others = [" ) == ("]
for a in attrs:
if a.eq_key:
cmp_name = f"_{a.name}_key"
# Add the key function to the global namespace
# of the evaluated function.
globs[cmp_name] = a.eq_key
lines.append(f" {cmp_name}(self.{a.name}),")
others.append(f" {cmp_name}(other.{a.name}),")
lines.append(
f" {cmp_name}(self.{a.name}) == {cmp_name}(self.{a.name})"
Tinche marked this conversation as resolved.
Show resolved Hide resolved
)
else:
lines.append(f" self.{a.name},")
others.append(f" other.{a.name},")

lines += [*others, " )"]
lines.append(f" self.{a.name} == other.{a.name}")
if a is not attrs[-1]:
lines[-1] = f"{lines[-1]} and"
lines.append(" )")
else:
lines.append(" return True")

Expand Down
2 changes: 1 addition & 1 deletion tests/strategies.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def _create_hyp_nested_strategy(draw, simple_class_strategy):
bare_attrs = st.builds(attr.ib, default=st.none())
int_attrs = st.integers().map(lambda i: attr.ib(default=i))
str_attrs = st.text().map(lambda s: attr.ib(default=s))
float_attrs = st.floats().map(lambda f: attr.ib(default=f))
float_attrs = st.floats(allow_nan=False).map(lambda f: attr.ib(default=f))
dict_attrs = st.dictionaries(keys=st.text(), values=st.integers()).map(
lambda d: attr.ib(default=d)
)
Expand Down