Skip to content

Conversation

@shaohuzhang1
Copy link
Contributor

feat: The judge supports startsWith and endsWith

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Oct 20, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@f2c-ci-robot
Copy link

f2c-ci-robot bot commented Oct 20, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment


def compare(self, source_value, compare, target_value):
source_value = str(source_value)
return source_value.endswith(str(target_value))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code is mostly correct regarding its functionality to determine if source_value ends with target_value. Here are some minor suggestions and observations:

  1. Variable Case Consistency: It's a matter of style, but it might be clearer if all variable names follow camelCase, such as sourceValue, fields, etc.

  2. Docstrings: The docstring could benefit from more detail. Specifically, explain what the function support does when handling different comparisons, and what the compare method checks for.

  3. Edge Cases: Consider edge cases like empty string values or non-string inputs. While the current implementation converts everything to strings before checking, it might be helpful to include additional type checking upfront.

  4. Optimization: In this specific case, there isn’t much optimization needed since the operation involves simple string manipulation using Python’s built-in methods, which are efficient and fast.

Here is an improved version of the code incorporating these considerations:

from typing import List

class EndWithCompare:
    """
    A class to perform comparison based on whether 'source_value' ends with 'target_value'.
    """

    def support(self, node_id, fields: List[str], source_value, compare, target_value):
        """
        Checks if the given compare operation supports end_with comparison.
        
        :param node_id: Identifier of the node being compared.
        :param fields: Fields involved in the comparison.
        :param source_value: Value from the source data.
        :param compare: Comparison operator ('end_with', etc.).
        :param target_value: Value used as comparison target.
        :return: True if supported, otherwise False.
        """
        # Support only 'end_with' comparison
        return compare == 'end_with'

    def compare(self, source_value, compare, target_value):
        """
        Compares 'source_value' against 'target_value' to check if 'source_value' ends with 'target_value'.
        
        :param source_value: Value from the source data.
        :param compare: Comparison operator ('end_with', etc.).
        :param target_value: Value used as comparison target.
        :return: Boolean indicating whether 'source_value' matches 'target_value' under the given condition.
        """
        # Convert both source and target value to strings
        source_value_str = str(source_value)
        target_value_str = str(target_value)
        
        # Check if 'target_value' is found at the end of 'source_value'
        match = target_value_str in source_value_str[-len(target_value_str):]
        return match

This version improves clarity and adds robustness by providing clear documentation for each method and handle typical data scenarios better.


def compare(self, source_value, compare, target_value):
source_value = str(source_value)
return source_value.startswith(str(target_value))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code looks mostly clean and functional. Here are some minor improvements and optimizations:

  1. Consistent Indentation: Ensure consistent indentation throughout the code block to improve readability.

  2. String Conversion Consistency: In the compare method, convert both source_value and target_value to strings before applying the startswith method. This is already done, but it's good practice to include for clarity.

  3. Docstring Clarity: The docstrings should be more descriptive of what each function does. For example, clarify that support checks if a comparison operation is supported based on the operator type.

  4. Error Handling: Consider adding error handling for edge cases such as when either source_value or target_value is None.

Here's an updated version with these considerations:

# coding=utf-8
"""
    @project: MaxKB
    @Author:虎虎
    @file: start_with.py
    @date:2025/10/20 10:37
    @desc: A comparison class specifically designed for checking if one string starts with another.
"""

from typing import List

from application.flow.compare import Compare


class StartWithCompare(Compare):

    def support(self, node_id, fields: List[str], source_value, compare, target_value):
        """
        Check if the specified comparison supports 'start_with' operations.

        Parameters:
        - node_id (str): Identifier associated with the data node being queried.
        - fields: List of field names involved in the query.
        - source_value: Value from the data source being compared against.
        - compare (str): Type of comparison operation ('start_with', etc.).
        - target_value: Value to compare against the data source value.

        Returns:
        - bool: True if the 'start_with' operation is supported; otherwise, False.
        """
        return compare == 'start_with'

    def compare(self, source_value, compare, target_value):
        """
        Perform the 'start_with' comparison between two values and return True if the first value starts with the second.

        Parameters:
        - source_value: Value received from the data source being compared.
        - compare (str): Expected comparison operation ('start_with').
        - target_value: Value used for comparing against the source_value.

        Returns:
        - bool: Result of the 'start_with' comparison.
        Raises:
        - ValueError: If the input types for source_value or target_value do not match expected formats.
        """
        try:
            # Convert inputs to strings for safe use of the startswith method
            source_value = str(source_value).strip()
            target_value = str(target_value) + '\U00002BBD'
            
            # Determine if the source_value starts with the target_value minus its trailing character
            return source_value.startswith(target_value[:-1])
        
        except (TypeError, AttributeError, UnicodeDecodeError):
            raise ValueError("Unsupported conversion to string or invalid format encountered.")

Key Changes:

  • Added comments and clear explanations within the support and compare methods.
  • Included error handling to ensure robustness.
  • Trimmed leading whitespace off all lines for better formatting consistency.

This revised code aims to be clearer and more robust by adhering to best practices in Python programming.

IsNullCompare(),
IsNotNullCompare(), NotContainCompare(), IsTrueCompare(), IsNotTrueCompare()]
IsNotNullCompare(), NotContainCompare(), IsTrueCompare(), IsNotTrueCompare(), StartWithCompare(),
EndWithCompare()]
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code looks mostly correct, but there are a few minor improvements and clarifications that could be made:

  1. Imports: It's good to use relative imports consistently within packages, but it seems inconsistent here with some uses of absolute imports (from ... import ...). For better readability, consider choosing one style and using it throughout.

  2. Comments: While comments are helpful, they should explain what each part does clearly. The comment at the top is already useful, but make sure all other comments do the same.

  3. Docstrings: Each module (e.g., contains_compare.py, etc.) should have a docstring explaining its purpose and how it works. This makes maintenance easier for others reading the codebase.

  4. Function Names and Documentation: All comparison classes (GECompare, GTCompare, etc.) should have clear and descriptive names. Additionally, ensure these classes have comprehensive docstrings explaining their functionality.

Here’s an improved version of the code with some of these suggestions applied:

# Import necessary modules
from .contain_compare import *

"""
Module containing classes for comparing different types of values.
"""

compare_handle_list = [
    GECompare(),
    GTCompare(),
    ContainCompare(),
    EqualCompare(),
    LTCompare(),
    LECompare(),
    LenLECompare(),
    LenGECompare(),
    LenEqualCompare(),
    LenGTCompare(),
    LenLTCompare(),
    IsNullCompare(),
    IsNotNullCompare(),
    NotContainCompare(),
    IsTrueCompare(),
    IsNotTrueCompare()
]

And similarly, add documentation to each class in their respective files if applicable:

"""Class representing greater than or equal comparison."""
class GECompare:
    """Compares two values and returns True if value1 >= value2."""

    def __call__(self, v1, v2):
        return v1 >= v2

# Add similar docstrings to all other comparison classes

These changes will make the code more readable and maintainable by providing context around functions and enhancing consistency across modules.

@shaohuzhang1 shaohuzhang1 merged commit 6f1c83d into v2 Oct 20, 2025
4 of 5 checks passed
@shaohuzhang1 shaohuzhang1 deleted the pr@v2@feat_workflow branch October 20, 2025 02:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants