Python 中受保护的方法调用?

问题描述 投票:0回答:4

我需要进行一系列调用,所有这些调用都可能引发异常,并且我需要一种保护调用的好方法。 我正在尝试找到一种更专业的方法来在 python 中执行以下操作:

def protected_call(method):
   result = None
   try:
       result= method()
   except:  pass

   return result
class Test():


  def terminate(): 
     protected_call(self.could_throw_exception)
     protected_call(self.receiver.stop)
     protected_call(self.connection.stop)
     #etc

有更好的方法吗?也许带有注释?

只是为了澄清,我不想想在原始方法上添加注释,即:

class Receiver():
  @protected
  def stop():
     print 'I dont want to do this'

class Test():
  @protected
  def could_throw_exception():
     print 'dont want this'
  def stop(): 
     self.could_throw_exception()
     self.receiver.stop()

这就是我想要的:

class Receiver():
  def stop():
     print 'I want this'

class Test():

  def could_throw_exception():
     print 'like this'

  '''This one cares about crashing'''
  def stop()
     self.could_throw_exception()
     self.receiver.stop()
     self.connection.stop()

  '''This one does not'''
  def terminate(): 
     #i want to define it at the call level.
     @protected
     self.could_throw_exception()
     @protected
     self.receiver.stop()
python exception
4个回答
3
投票

正如 nmichaels 所建议的,这种事情最好通过

with
语句来处理。

@contextlib.contextmanager
def suppress_exceptions(*exceptions):
    if not exceptions:
        exceptions = Exception
    try:
        yield
    except exceptions:
        # You would log an error here
        # If you have logging in your application
        pass

with suppress_exceptions():
    1/0

print("Ignored the exception!")

with suppress_exceptions(IOError):
    1/0

# The second one will let the exception through

3
投票

装饰器非常适合这个:

def protected_call(method):
    def wrapper(*args, **kwargs):
        try:
            return method(*args, **kwargs)
        except:
            pass
    return wrapper

使用示例:

@protected_call
def foo():
    raise Exception()

# nothing is being raised
foo()

1
投票

听起来像是装饰师的工作

def protected_call(func):
    def inner(*args, **kw):
        try:
            return func(*args, **kw)
    except:
            pass
    return inner

class Test():

    @protected_call
    def throws_exception(self):
        print 1/0

    @protected_call
    def no_exception(self):
        print 4

    def sometimes_need_exception(self):
        print 5
    protected_sometimes_need_exception = protected_call(sometimes_need_exception)

    def stop(self):
        self.throws_exception()
    self.no_exception()

0
投票

至少记录异常似乎是一个有用的功能,否则您将如何控制意外错误......?

© www.soinside.com 2019 - 2024. All rights reserved.