I have a lot of getter functions like this:
get_property_a(default=None):
try:
self.data.get("field_1")[0].get("a")
except Exception as e:
return default
get_property_b(default=None):
try:
self.data.get("field_2")[0].get("b")
except Exception as e:
return default
...
Is there a way to not wrapping all the getters in try/except? It would be nice if it is some kind of annotation like this:
@silent_exec(default=None)
def get_property_b():
self.data.get("field_2")[0].get("b")
Thanks
You can do this by writing your own decorator:
import functools
def silent_exec(default=None):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs):
except Exception:
return default
return wrapper
return decorator
With that said, I'd be very wary of using this. You should very rarely be catching all exceptions (as we've done here). Normally you it's better to specify a tuple of exceptions that you actually expect and know how to handle...
import functools
def silent_exec(exceptions, default=None):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs):
except exceptions:
return default
return wrapper
return decorator
@silent_exec((IndexError, KeyError), default=None)
def get_property_b():
self.data.get("field_2")[0].get("b")
This way, you don't end up catching/silencing programming errors -- those will still get raised, you can look at them in the logs or wherever they get reported and you can go back in and fix them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.