-
Notifications
You must be signed in to change notification settings - Fork 2.3k
feat: New condition for determining whether the discriminator is true or not #2809
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
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# coding=utf-8 | ||
""" | ||
@project: MaxKB | ||
@Author:虎 | ||
@file: is_not_true.py | ||
@date:2025/4/7 13:44 | ||
@desc: | ||
""" | ||
from typing import List | ||
|
||
from application.flow.step_node.condition_node.compare import Compare | ||
|
||
|
||
class IsNotTrueCompare(Compare): | ||
|
||
def support(self, node_id, fields: List[str], source_value, compare, target_value): | ||
if compare == 'is_not_ture': | ||
return True | ||
|
||
def compare(self, source_value, compare, target_value): | ||
try: | ||
return source_value is False | ||
except Exception as e: | ||
return False | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The provided code有几个潜在的问题和技术优化建议:
Here’s an enhanced version with these considerations: # coding=utf-8
"""
@project: MaxKB
@Author:虎
@file: is_not_true.py
@date:2025/4/7 13:44
@desc: Custom compare condition based on 'is not true'.
"""
from typing import List
from application.flow.step_node.condition_node.compare import Compare
class IsNotTrueCompare(Compare):
def support(self, node_id: str, fields: List[str], source_value, compare_type: str, target_value: any) -> bool:
"""
Determines if 'source_value' does not equal 'target_value'.
Args:
self: Instance of IsNotTrueCompare.
node_id (str): Identifier of the current node.
fields: List of field names associated with the condition.
source_value: Value to evaluate as truthiness.
compare_type: Type of comparison ('is_not_true').
target_value: Target value to compare against.
Returns:
bool: True if 'source_value' evaluates to false, False otherwise.
"""
if isinstance(source_value, bool):
return not source_value
supported_comparisons = {'is_not_true': True}
# Check if the given comparison type supports logical inversion
if compare_type in supported_comparisons:
return not source_value
raise ValueError(f"Unsupported comparison type '{compare_type}'")
def compare(
self,
source_value: bool,
compare_type: str,
target_value: any
) -> bool:
"""
Performs the actual comparison logic.
Args:
source_value (bool): Boolean value to evaluate as truthiness.
compare_type: Comparison type (ignored since we invert boolean values).
target_value: Target value (unused since we invert boolean values).
Returns:
bool: Logical inverse result of evaluating boolean value 'source_value'.
"""
if not isinstance(source_value, bool):
# Fallback to standard non-null evaluation
return bool(source_value)
return not source_value # Simple inverted boolean logic This enhanced version provides a more structured approach to handling boolean comparison logic with clear documentation and improved error checking. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# coding=utf-8 | ||
""" | ||
@project: MaxKB | ||
@Author:虎 | ||
@file: IsTrue.py | ||
@date:2025/4/7 13:38 | ||
@desc: | ||
""" | ||
from typing import List | ||
|
||
from application.flow.step_node.condition_node.compare import Compare | ||
|
||
|
||
class IsTrueCompare(Compare): | ||
|
||
def support(self, node_id, fields: List[str], source_value, compare, target_value): | ||
if compare == 'is_ture': | ||
return True | ||
|
||
def compare(self, source_value, compare, target_value): | ||
try: | ||
return source_value is True | ||
except Exception as e: | ||
return False | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The provided code has several issues that need to be addressed:
Here’s an improved version of the code with some recommendations: # coding=utf-8
"""
@project: MaxKB
@Author:虎
@file: IsTrue.py
@date:2025/4/7 13:38
@desc:
"""
from typing import List
from application.flow.step_node.condition_node.compare import Compare
class IsTrueCompare(Compare):
def support(self, node_id:str, fields:List[str], source_value, compare_type) -> bool:
# Ensure compare_type is one of the allowed values
supported_types = ['is_true', 'is_false']
if compare_type.lower() not in supported_types:
raise ValueError(f"Unsupported comparison type '{compare_type}'. Supported types are {supported_types}")
# Return True if the comparison type matches the input
return compare_type.lower() == 'is_true'
def compare(self, source_value, compare_type, target=None):
"""
Compares a source value against a specified condition using the given comparison type.
:param source_value: The value to be compared.
:param compare_type: A string specifying the type of comparison ('is_true' or 'is_false').
:param target: Ignored.
:return: True if the comparison applies to source_value based on compare_type, otherwise False.
"""
if source_value is None or not isinstance(source_value, bool):
return False
# Perform specific comparisons based on compare_type
if compare_type.upper() == 'IS_TRUE':
return source_value
elif compare_type.upper() == 'IS_FALSE':
return not source_value Changes Made:
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The code looks mostly correct for its intended purpose of checking if a value "is true" based on the
Here's an optimized version of the code with these improvements: # -*- coding: utf-8 -*-
"""
@project: MaxKB
@author:虎
@file:IsTrue.py
@date:2025/4/7 13:38
@desc:
"""
from typing import List
from application.flow.step_node.condition_node.compare import BaseConditionNode
class IsTrueCompare(BaseConditionNode):
def support(self, node_id, fields: List[str], source_value, compare_strategy, target_value) -> bool:
"""
Check if the source value meets an 'is_true' condition against the target value.
Args:
node_id (str): Node identifier.
fields (List[str]): Not used in this implementation.
source_value: Value to be compared.
compare_strategy (str): Determines how comparison is performed ('is_true', etc.
target_value: Not used in this specific implementation.
Returns:
bool: True if the condition is met, False otherwise.
"""
return compare_strategy.lower() == 'is_true'
def compare(self, source_value, condition, target_value=None) -> bool:
"""
Compare the source value against the target using the specified condition.
Since 'is_true' requires direct truthiness, the target should not be provided.
Args:
source_value: Boolean value to be checked.
condition (any): Comparison logic to evaluate. In this case, it should be a string.
target_value: Not used in this specific implementation.
Raises:
ValueError: If the condition is not 'is_true'.
Returns:
bool: True if the condition evaluates to True, False otherwise.
"""
if condition != 'is_true':
raise ValueError(f"Unsupported comparison strategy '{condition}'. Use 'is_true'.")
return bool(source_value) Key Changes:
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,14 +25,8 @@ | |
size="small" | ||
style="width: 60px; margin: 0 8px" | ||
> | ||
<el-option | ||
:label="$t('views.applicationWorkflow.condition.AND')" | ||
value="and" | ||
/> | ||
<el-option | ||
:label="$t('views.applicationWorkflow.condition.OR')" | ||
value="or" | ||
/> | ||
<el-option :label="$t('views.applicationWorkflow.condition.AND')" value="and" /> | ||
<el-option :label="$t('views.applicationWorkflow.condition.OR')" value="or" /> | ||
</el-select> | ||
<span>{{ | ||
$t('views.applicationWorkflow.nodes.conditionNode.conditions.label') | ||
|
@@ -56,9 +50,7 @@ | |
ref="nodeCascaderRef" | ||
:nodeModel="nodeModel" | ||
class="w-full" | ||
:placeholder=" | ||
$t('views.applicationWorkflow.variable.placeholder') | ||
" | ||
:placeholder="$t('views.applicationWorkflow.variable.placeholder')" | ||
v-model="condition.field" | ||
/> | ||
</el-form-item> | ||
|
@@ -94,7 +86,11 @@ | |
</el-col> | ||
<el-col :span="6"> | ||
<el-form-item | ||
v-if="condition.compare !== 'is_null' && condition.compare !== 'is_not_null'" | ||
v-if=" | ||
!['is_null', 'is_not_null', 'is_true', 'is_not_true'].includes( | ||
condition.compare | ||
) | ||
" | ||
:prop="'branch.' + index + '.conditions.' + cIndex + '.value'" | ||
:rules="{ | ||
required: true, | ||
|
@@ -137,7 +133,8 @@ | |
</el-card> | ||
</template> | ||
<el-button link type="primary" @click="addBranch"> | ||
<el-icon class="mr-4"><Plus /></el-icon> {{ $t('views.applicationWorkflow.nodes.conditionNode.addBranch') }} | ||
<el-icon class="mr-4"><Plus /></el-icon> | ||
{{ $t('views.applicationWorkflow.nodes.conditionNode.addBranch') }} | ||
</el-button> | ||
</el-form> | ||
</NodeContainer> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The code looks mostly clean overall, with only minor cosmetic issues to be addressed. Here are the suggestions:
Here's a suggested version of the updated code: <template>
<!-- Existing template structure -->
<!-- ... -->
<!-- Button block remains unchanged -->
</template>
<script setup lang="ts">
// Import necessary dependencies at the top
const addBranch = () => {};
</script> These changes focus primarily on simplification and clarity without significant impact on functionality. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There are no significant irregularities or potential issues detected in the provided code snippet. However, here is a few optimization suggestions:
Here's an optimized version of your code: <template>
<!-- ... existing template content ...
<div class="mb-4">
<el-cascader
@focus="$refs.nodeCascaderRef.focus()"
:options="variableOptions"
ref="nodeCascaderRef"
:nodeModel="nodeModel"
class="w-full"
v-model="condition.field"
:placeholder="$t('views.applicationWorkflow.variable.placeholder')"
/>
</div>
<el-button link type="primary" @click="addBranch">
<el-icon class="mr-4"><Plus /></el-icon> {{ $t('views.applicationWorkflow.nodes.conditionNode.addBranch') }}
</el-button>
</el-form>
</NodeContainer>
</template>
<script>
export default {
data() {
return {
variableOptions: [], // Initialize options array
branches: [], // Assume you have a branches array
condition: {},
};
},
methods: {
addBranch() {
if (Array.isArray(this.branches)) {
this.branches.push({}); // Add new branch object
} else {
this.branches = [{ value: '', compare: '==' }]; // Alternatively, initialize array or single branch
}
},
},
};
</script> By making these adjustments, you reduce redundancy and enhance readability while keeping the codebase maintainable. |
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The provided Python code has several issues that need to be addressed:
Syntax Error: The line
@@ -0,0 +1,24 @@
seems to be an SVN diff command and should not appear at the start of a file when you're checking the syntax.Python Version Compatibility: Using Unicode-specific encoding (
# coding=utf-8
) might cause compatibility issues with older versions of Python (e.g., Python 2), but it's generally safe in modern Python environments since many newer codecs like UTF-8 are supported across different platforms.Docstring: There is no consistent documentation style between comments and docstrings. This can make the code harder to understand and maintain.
Class Name and Method Names: Class names should follow PEP 8 standards, which recommend snake_case instead of CamelCase. Similarly, method names should also use camelCase.
Import Statements: Import statements should be placed after class definitions or function declarations, according to best practices for modularity.
Exception Handling: While catching exceptions helps in error handling, they come with a cost. It’s better to handle specific exceptions that may occur without affecting other parts of the program. In this case, a
ValueError
could provide more context about what went wrong with the source value.Logic Check: The logic for determining if something is "not true" isn't clear from the implementation. It currently checks if
source_value
is equal toFalse
, but there might have been intended to compare against another value. Assuming the intent was to return whether thesource_value
evaluates to a boolean false, the method signature needs to match and the comparison should be done accordingly.Here's a revised version of the code addressing these issues:
Changes Made:
IsNotTrueCompare
.functools.lru_cache
for memory efficiency.TypeError
.