Can use of `exec()` and `locals()` be avoided in `processed_property`'s `cast_type()` function?
brocksam opened this issue · comments
Sam Brockie commented
Code safety may be improved if used of exec()
and locals()
is avoided. See:
pyproprop/pyproprop/processed_property.py
Lines 136 to 165 in 8aeb8cc
def cast_type(value): | |
"""Enforce type casting of property value to be set to specific type. | |
Parameters | |
---------- | |
value : obj | |
Property object value for setting. | |
Returns | |
------- | |
obj | |
Supplied value cast to the specified type | |
Raises | |
------ | |
ValueError | |
If the casting fails. | |
TypeError | |
If the casting fails. | |
""" | |
cast_str = f"processed_value = {expected_type.__name__}({value})" | |
try: | |
exec(cast_str) | |
except (ValueError, TypeError) as e: | |
name_str = generate_name_description_error_message() | |
msg = (f"{name_str} must be a {repr(expected_type)}, instead got " | |
f"a {repr(type(value))} which cannot be cast.") | |
raise e(msg) | |
return locals()['processed_value'] |