Conversation
| ] | ||
|
|
||
|
|
||
| class Example2Model(Model): |
Check warning
Code scanning / CodeQL
`__eq__` not overridden when adding attributes Warning
Show autofix suggestion
Hide autofix suggestion
Copilot Autofix
AI about 7 hours ago
In general, when a subclass adds new state and the superclass defines __eq__, the subclass should override __eq__ (and ideally __ne__) to extend the equality comparison so that the new attributes are considered. This is done by first delegating to super().__eq__ to reuse the base comparison, and then comparing the subclass-specific attributes. __ne__ can simply be defined as the logical negation of __eq__.
For this specific case, we should modify Example2Model in simopt/models/example.py so that it defines __eq__ and __ne__. The __eq__ implementation should:
- Return
NotImplementedifotheris not anExample2Modelinstance, to allow symmetric dispatch. - Call
super().__eq__(other)and, if that returnsNotImplemented, propagate it. - If the base comparison is
False, returnFalse. - If the base comparison is
True, additionally compareself.noise_modelandother.noise_model.
This preserves existing equality semantics from Model and only tightens them by including noise_model. For __ne__, define it as return not self.__eq__(other) while handling NotImplemented properly (if __eq__ returns NotImplemented, propagate that instead of negating it). No new imports are necessary; we can add these methods directly inside the Example2Model class, after __init__ (placement inside the class body is flexible, but keeping them near initialization is clear).
| @@ -228,6 +228,26 @@ | ||
| super().__init__(fixed_factors) | ||
| self.noise_model = Normal() | ||
|
|
||
| def __eq__(self, other: object) -> bool: | ||
| """Extend base equality to include the noise model.""" | ||
| if not isinstance(other, Example2Model): | ||
| return NotImplemented | ||
|
|
||
| base_eq = super().__eq__(other) | ||
| if base_eq is NotImplemented: | ||
| return NotImplemented # type: ignore[return-value] | ||
| if not base_eq: | ||
| return False | ||
|
|
||
| return self.noise_model == other.noise_model | ||
|
|
||
| def __ne__(self, other: object) -> bool: | ||
| """Negation of __eq__.""" | ||
| eq_result = self.__eq__(other) | ||
| if eq_result is NotImplemented: | ||
| return NotImplemented # type: ignore[return-value] | ||
| return not eq_result | ||
|
|
||
| def before_replicate(self, rng_list: list[MRG32k3a]) -> None: # noqa: D102 | ||
| self.noise_model.set_rng(rng_list[0]) | ||
|
|
No description provided.