Create __eq__ method for *cls* with *attrs*.
(attrs: list)
| 1707 | |
| 1708 | |
| 1709 | def _make_eq_script(attrs: list) -> tuple[str, dict]: |
| 1710 | """ |
| 1711 | Create __eq__ method for *cls* with *attrs*. |
| 1712 | """ |
| 1713 | attrs = [a for a in attrs if a.eq] |
| 1714 | |
| 1715 | lines = [ |
| 1716 | "def __eq__(self, other):", |
| 1717 | " if other.__class__ is not self.__class__:", |
| 1718 | " return NotImplemented", |
| 1719 | ] |
| 1720 | |
| 1721 | globs = {} |
| 1722 | if attrs: |
| 1723 | lines.append(" return (") |
| 1724 | for a in attrs: |
| 1725 | if a.eq_key: |
| 1726 | cmp_name = f"_{a.name}_key" |
| 1727 | # Add the key function to the global namespace |
| 1728 | # of the evaluated function. |
| 1729 | globs[cmp_name] = a.eq_key |
| 1730 | lines.append( |
| 1731 | f" {cmp_name}(self.{a.name}) == {cmp_name}(other.{a.name})" |
| 1732 | ) |
| 1733 | else: |
| 1734 | lines.append(f" self.{a.name} == other.{a.name}") |
| 1735 | if a is not attrs[-1]: |
| 1736 | lines[-1] = f"{lines[-1]} and" |
| 1737 | lines.append(" )") |
| 1738 | else: |
| 1739 | lines.append(" return True") |
| 1740 | |
| 1741 | script = "\n".join(lines) |
| 1742 | |
| 1743 | return script, globs |
| 1744 | |
| 1745 | |
| 1746 | def _make_order(cls, attrs): |