brocksam / pyproprop

Write classes with lots of similar simple defensive properties without the boilerplate

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can use of `exec()` and `locals()` be avoided in `processed_property`'s `cast_type()` function?

brocksam opened this issue · comments

Code safety may be improved if used of exec() and locals() is avoided. See:

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']