-
Notifications
You must be signed in to change notification settings - Fork 2.1k
fix: The float values collected by the form will be treated as ints when the decimal part is 0, resulting in a type error #2601
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 all commits
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 |
---|---|---|
|
@@ -33,9 +33,9 @@ def write_context(step_variable: Dict, global_variable: Dict, node, workflow): | |
|
||
def valid_reference_value(_type, value, name): | ||
if _type == 'int': | ||
instance_type = int | ||
instance_type = int | float | ||
elif _type == 'float': | ||
instance_type = float | ||
instance_type = float | int | ||
elif _type == 'dict': | ||
instance_type = dict | ||
elif _type == 'array': | ||
|
@@ -56,6 +56,10 @@ def convert_value(name: str, value, _type, is_required, source, node): | |
value[0], | ||
value[1:]) | ||
valid_reference_value(_type, value, name) | ||
if _type == 'int': | ||
return int(value) | ||
if _type == 'float': | ||
return float(value) | ||
return value | ||
try: | ||
if _type == 'int': | ||
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 several potential improvements and issues in your code: Improvements:
Issues and Optimization Suggestions:
Here's a revised version incorporating some of these suggestions: from typing import Any, Callable, Union
class WorkflowStepVariable(Dict[str, Any]):
def __init__(self):
super().__init__()
def valid_reference_value(_type: str, value: Any, name: str) -> bool:
"""Check if the given value matches the specified type."""
match (_type, value):
case ('int', int()):
return True
case ('float', float()):
return True
case ('dict', dict()):
return True
case ('tuple', tuple() | range()): # Check for tuples or ranges
return True
case _: # Fallback for invalid cases
raise ValueError(f"Invalid reference value '{name}' has type {type(value).__name__}, expected {str.union(*_types)}")
def convert_value(name: str, value: Any, _type: str, is_required:bool=False, source='workflow'):
"""Convert the value based on its type."""
_typename = _type.lower()
valid_reference_value(_typename, value, name)
if _typename == 'int':
return int(value)
elif _typename == 'float':
return float(value)
elif _typename == 'list':
# Assuming a list can contain only elements of the same type
if isinstance(value[0], float) or isinstance(value[0], int):
return value.copy()
else:
raise TypeError("List contains non-int/float values")
else:
raise AttributeError(f"No conversion defined for type {_typename}")
# Usage example
step_variable = {...}
global_variable = {...}
write_context(step_variable, global_variable, None, None) This revision ensures clarity, robustness, and efficiency while adhering to best practices for type and validation in Python. |
||
|
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 code has several potential issues and optimizations:
Inconsistent type handling:
valid_reference_value
checks for'int'
,'float'
,'dict'
, and'array'
. It then directly returns types likeint
orfloat
without any further validation.Missing error handling for invalid input:
_type
is encountered.Redundant operations:
Code repetition:
Potential type errors during conversion:
Documentation update:
Here's a revised version of the code with some improvements:
Key Changes:
int
,string
, etc.) based on actual use case requirements.convert_if_necessary()
function for clarity.