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

Allow expr_matches to better handle presence of extra data #93

Merged
merged 5 commits into from
Aug 28, 2024

Conversation

PhilReinhold
Copy link
Collaborator

I am creating oqpy variables from some other representation, and I wanted to attach some extra data to the oqpy variables to indicate their provenance. When I did this, I got failures from expr_matches since it's method of traversing the __dict__ recursively is not applicable to my data, which has reference cycles.

I've modified expr_matches so that it short circuits on object identity, and so that it only descends into obj.__dict__ for objects from the oqpy package, rather than any externally produced data.

oqpy/base.py Outdated
@@ -328,7 +330,7 @@ def expr_matches(a: Any, b: Any) -> bool:
if a.keys() != b.keys():
return False
return all(expr_matches(va, b[k]) for k, va in a.items())
if hasattr(a, "__dict__"):
if hasattr(a, "__dict__") and type(a).__module__.startswith("oqpy"):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this mean that oqpy classes shouldn't be subclassed outside of these modules (vaguely what sealed means in some other languages)?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, good point I hadn't considered that. Passing in a trivial subclass probably shouldn't break things.

Thinking about it more, we only need to avoid using a == b test when it's an instance of OQPyExpression since it's subtypes of that class which have __eq__ overridden, so I've changed this clause to look for that instead.

I've added a test for the case of using a trivial subclass.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also have added a method to allow subclasses to control how matching works if required

Copy link
Contributor

@braised-babbage braised-babbage left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, thanks for the update

@PhilReinhold PhilReinhold merged commit 6efb6f5 into main Aug 28, 2024
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants