简体   繁体   English

如何在try / catch中自动包装函数调用?

[英]How to auto wrap function call in try / catch?

I have a lot of getter functions like this: 我有很多像这样的getter函数:

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? 有没有办法在try / except中包装所有getter? 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. 这样,您最终不会捕获/沉默编程错误 - 这些错误仍然会被提升,您可以在日志中或在报告的任何位置查看它们,您可以返回并修复它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM