Replies: 4 comments 1 reply
-
I like both solutions In general, I am fine(ish) with code duplication in testing and stuff like confirmation/error-handling. But maybe it is getting out of hand with bots telling us to do so much of it? |
Beta Was this translation helpful? Give feedback.
-
Yeah, in the tests I was fine with. I was more feeling that the input to the functions started to feel a bit off with the multiple if statement checks. I like the decorators better, as you can stack them for different variables and the runtime error is clear enough. Traceback (most recent call last):
File "example.py", line 47, in <module>
calculate_partial_pressure(concentration=-1.0, molar_mass=0.028, temperature=300.0)
File "example.py", line 24, in wrapper
validate_positive(value, name)
File "example.py", line 9, in validate_positive
raise ValueError(f"{name} must be positive.")
ValueError: concentration must be positive. |
Beta Was this translation helpful? Give feedback.
-
Okay, then let's have a particula-wide decorator? What cases do we need to cover?
Then, we can have from functools import wraps
import numpy as np
def validate_inputs(dict_args):
"""
A decorator to validate that specified arguments are positive.
Arguments:
arg_names: List of argument names to validate.
Returns:
A decorator for input validation.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Map argument names to values
arg_dict = func.__annotations__
for name, comp in dict_args.items():
value = kwargs.get(name, args[list(arg_dict).index(name)])
if comp == "positive":
validate_positive(value, name)
elif comp == "negative":
...
return func(*args, **kwargs)
return wrapper
return decorator then have decorate functions with like |
Beta Was this translation helpful? Give feedback.
-
Btw, do you know if we can use multiple decorators? |
Beta Was this translation helpful? Give feedback.
-
Is there a better way to validate inputs for functions. So we don't duplicate.
GPT thinks, decorators or helper functions (example below). I just want the error to raise correctly so you know which function/variable is the problem.
thoughts @mahf708 ?
To avoid duplicating validation logic across multiple functions, you can use helper functions or decorators for reusable input validation. This modular approach reduces repetition and improves maintainability. Here's an improved structure for your use case:
1. Helper Functions
Define utility functions to handle input validation. This centralizes the validation logic and keeps your main function clean.
2. Using Decorators
Decorators allow you to apply validation to multiple functions without modifying their code. Here's an example:
Beta Was this translation helpful? Give feedback.
All reactions