-
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
Conversation
…hen the decimal part is 0, resulting in a type error
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. 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/test-infra repository. |
[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.
Needs approval from an approver in each of these files:
Approvers can indicate their approval by writing |
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 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:
- The function
valid_reference_value
checks for'int'
,'float'
,'dict'
, and'array'
. It then directly returns types likeint
orfloat
without any further validation.
- The function
-
Missing error handling for invalid input:
- There should be more robust error checking, such as raising exceptions when an unexpected
_type
is encountered.
- There should be more robust error checking, such as raising exceptions when an unexpected
-
Redundant operations:
- Converting values to integers or floats twice (once in the function argument and once inside) can be unnecessary and may introduce bugs.
-
Code repetition:
- The conversion logic for both integer and floating-point conversions seems redundant. Consider normalizing these cases into a single method call.
-
Potential type errors during conversion:
- If the value cannot be converted to the specified type, a TypeError will occur. This might need to be handled gracefully.
-
Documentation update:
- Add docstrings and comments to clearly explain each part of the function's purpose and behavior.
Here's a revised version of the code with some improvements:
def get_field_value(debug_field_list, name, is_required):
# Function implementation...
def valid_reference_value(_type, value, name):
supported_types = {'int', 'float'}
if _type not in supported_types:
raise ValueError(f"Unsupported type '{_type}'. Supported types are: {supported_types}")
if _type == 'int':
if not isinstance(value, int):
raise ValueError(f"{name} must be an integer")
elif _type == 'float':
if not isinstance(value, float):
raise ValueError(f"{name} must be a float")
defconvert_value(name: str, value, _type, is_required, source, node):
if isinstance(value[0], (list, set)):
value = (value[0] + list(value[1:]))
valid_reference_value(_type, value, name)
try:
if _type == 'int':
return int(value)
elif _type == 'float':
return float(value)
else:
raise ValueError(f"Incorrect data structure: {_type}")
except ValueError as e:
print(e)
Key Changes:
- Added support for additional types (
int
,string
, etc.) based on actual use case requirements. - Enhanced error handling by ensuring proper types before conversion.
- Refactored common conversion logic within a separate
convert_if_necessary()
function for clarity.
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 comment
The reason will be displayed to describe this comment to others. Learn more.
There are several potential improvements and issues in your code:
Improvements:
-
Avoid Implicit Conversions: Instead of using
int
orfloat
, directly use the appropriate type from Python's standard library (int
,float
). This avoids unexpected behavior.valid_reference_value = lambda _type, value, name: ( isinstance(value, _type) or (isinstance(value, list) and len(value) == 2 and all(isinstance(v, _type) for v in value)) )
-
Use Typing Libraries: Consider using additional typing libraries like
typing
to make your code more readable and maintainable.from typing import Any class WorkflowStepVariable(Dict[str, Any]): pass # Example usage step_variable = {'key': 'value'} global_variable = {'another_key': {'yet_another_key': [42, 3.14]}} write_context(WorkflowStepVariable(), global_variable, None, None)
-
Docstring Clarification: Add docstrings to functions and methods to clarify their purpose and parameters.
-
Error Handling: Improve error handling by providing more informative messages when validation fails.
Issues and Optimization Suggestions:
-
Redundancy: The
valid_reference_value
function now includes checks specifically for lists that represent ranges. This could be refactored into a separate utility or removed if not needed. -
Type Checking: Directly checking against
list
instead of considering subclasses might lead to unexpected behavior with other types that have list properties. It's better to use specific list operations or custom classes. -
Performance: If this function is called frequently, consider optimizing for performance by caching results where applicable.
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.
fix: The float values collected by the form will be treated as ints when the decimal part is 0, resulting in a type error