Re: [PR] feat: Add comparison methods to c_class decorator [tvm-ffi]
junrushao closed pull request #421: feat: Add comparison methods to c_class decorator URL: https://github.com/apache/tvm-ffi/pull/421 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
Re: [PR] feat: Add comparison methods to c_class decorator [tvm-ffi]
junrushao commented on PR #421: URL: https://github.com/apache/tvm-ffi/pull/421#issuecomment-4100495235 Closed as superseded by existing works. Thanks again @Dayuxiaoshui for the effort and greatly appreciate your time! -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
Re: [PR] feat: Add comparison methods to c_class decorator [tvm-ffi]
Dayuxiaoshui commented on PR #421: URL: https://github.com/apache/tvm-ffi/pull/421#issuecomment-3822242571 @junrushao -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] - To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
Re: [PR] feat: Add comparison methods to c_class decorator [tvm-ffi]
gemini-code-assist[bot] commented on code in PR #421:
URL: https://github.com/apache/tvm-ffi/pull/421#discussion_r2724029320
##
python/tvm_ffi/dataclasses/field.py:
##
@@ -160,11 +166,14 @@ class PyBase:
raise TypeError("`init` must be a bool")
if not isinstance(repr, bool):
raise TypeError("`repr` must be a bool")
+<<< HEAD
Review Comment:

There appears to be an unresolved merge conflict marker `<<< HEAD` left
in the code. This will cause a syntax error and needs to be removed.
##
python/tvm_ffi/dataclasses/_utils.py:
##
@@ -162,7 +162,189 @@ def method_repr(type_cls: type, type_info: TypeInfo) ->
Callable[..., str]:
return __repr__
-def method_init(_type_cls: type, type_info: TypeInfo) -> Callable[..., None]:
+def method_eq(type_cls: type, type_info: TypeInfo) -> Callable[..., bool]:
+"""Generate an ``__eq__`` method that compares all fields with
``compare=True``.
+
+The generated method compares all fields with ``compare=True`` in the order
+they appear in the type hierarchy.
+"""
+# Step 0. Collect all fields from the type hierarchy
+fields = _get_all_fields(type_info)
+
+# Step 1. Filter fields that should be compared
+compare_fields: list[str] = []
+for field in fields:
+assert field.name is not None
+assert field.dataclass_field is not None
+if field.dataclass_field.compare:
+compare_fields.append(field.name)
+
+# Step 2. Generate the eq method
+if not compare_fields:
+# No fields to compare, all instances are equal
+body_lines = ["return True"]
+else:
+# Build field comparisons
+comparisons = " and ".join(
+f"self.{field_name} == other.{field_name}" for field_name in
compare_fields
+)
Review Comment:

Generating a long string of `and` comparisons can be less efficient and
harder to read than tuple comparison. Python's tuple comparison is implemented
in C and is generally faster for this kind of lexicographical comparison. You
can simplify this by comparing tuples of field values.
```python
comparisons = f"({', '.join(f'self.{f}' for f in compare_fields)},)
== ({', '.join(f'other.{f}' for f in compare_fields)},)"
```
##
tests/python/test_dataclasses_c_class.py:
##
@@ -184,3 +185,92 @@ def test_field_kw_only_with_default() -> None:
def test_kw_only_sentinel_exists() -> None:
assert isinstance(KW_ONLY, _KW_ONLY_TYPE)
+
+
+def test_cxx_class_eq() -> None:
+"""Test that eq=True generates __eq__ and __ne__ methods."""
+# Use the already registered _TestCxxClassBase which has eq=True by default
+obj1 = _TestCxxClassBase(v_i64=123, v_i32=456)
+obj2 = _TestCxxClassBase(v_i64=123, v_i32=456)
+obj3 = _TestCxxClassBase(v_i64=789, v_i32=456)
+
+# Test __eq__
+assert obj1 == obj2
+assert not (obj1 == obj3)
+
+# Test __ne__
+assert obj1 != obj3
+assert not (obj1 != obj2)
+
+# Test with different types
+assert obj1 != "not an object"
+assert not (obj1 == "not an object")
+
+
+def test_cxx_class_order() -> None:
+"""Test that order=True generates ordering methods."""
+from tvm_ffi.dataclasses import c_class
+
+# Create a test class with order=True using a different type key
+# We need to use a type that supports ordering, so we'll test with
_TestCxxClassDerived
+# which should inherit comparison methods if order=True is set
+# For now, let's test that ordering methods can be generated by checking
if they exist
+# on a class that was registered with order=True
+# Note: Since _TestCxxClassBase doesn't have order=True, we'll test the
functionality
+# by creating a new class that would have order=True if we could register
it
+# Instead, let's verify that the methods would be generated correctly by
testing
+# the comparison logic on _TestCxxClassBase instances
+obj1 = _TestCxxClassBase(v_i64=1, v_i32=2)
+obj2 = _TestCxxClassBase(v_i64=1, v_i32=3)
+obj3 = _TestCxxClassBase(v_i64=2, v_i32=1)
+obj4 = _TestCxxClassBase(v_i64=1, v_i32=2)
+
+# Check if ordering methods exist (they might not if order=False was used)
+has_ordering = any(method in _TestCxxClassBase.__dict__ for method in
["__lt__", "__le__", "__gt__", "__ge__"])
+
+if has_ordering:
+# Test __lt__ (less than)
+assert obj1 < obj2 # v_i64 equal, v_i32: 2 < 3
+assert obj1 < obj3 # v_i64: 1 < 2
+assert not (obj1 < obj4) # equal
+
+# Test __le__ (less than or equal)
+assert obj1 <= obj2
+assert obj1 <= obj4 # equal
+assert not (obj2 <= obj1)
+
+# Test __gt__ (greater than)
+assert obj2 > obj1
+assert obj3 > obj1
+asse
Re: [PR] feat: Add comparison methods to c_class decorator [tvm-ffi]
gemini-code-assist[bot] commented on PR #421: URL: https://github.com/apache/tvm-ffi/pull/421#issuecomment-3794437718 ## Summary of Changes Hello @Dayuxiaoshui, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the `c_class` decorator by integrating robust comparison capabilities. It allows users to define how instances of FFI-bound C++ classes are compared in Python, offering flexibility through class-level flags for equality and ordering, and field-level control to specify which attributes participate in these comparisons. This change streamlines the process of creating Pythonic interfaces for C++ types that require comparison logic. ### Highlights * **Comparison Method Generation**: Introduced new `eq` and `order` parameters to the `c_class` decorator, allowing automatic generation of `__eq__`, `__ne__`, `__lt__`, `__le__`, `__gt__`, and `__ge__` methods for FFI-bound classes. * **Field-level Comparison Control**: Added a `compare` parameter to the `field()` function, enabling fine-grained control over which fields are included in the generated comparison methods. * **Core Logic Implementation**: Implemented `method_eq`, `method_ne`, and `method_order` functions in `_utils.py` to dynamically generate the Python comparison methods based on the class's fields and the new `compare` attribute. * **Comprehensive Testing**: Added new test cases to validate the correctness and behavior of the generated equality and ordering methods, including scenarios with different field values and types. 🧠**New Feature in Public Preview:** You can now enable **Memory** to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.** Using Gemini Code Assist The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either `/gemini ` or `@gemini-code-assist `. Below is a summary of the supported commands on the current page. Feature | Command | Description --- | --- | --- Code Review | `/gemini review` | Performs a code review for the current pull request in its current state. Pull Request Summary | `/gemini summary` | Provides a summary of the current pull request in its current state. Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments. Help | `/gemini help` | Displays a list of available commands. Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a `.gemini/` folder in the base of the repository. Detailed instructions can be found [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG). You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the [Gemini Code Assist IDE Extension](https://cloud.google.com/products/gemini/code-assist). [^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487). -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: us...
