General decorator to wrap try except in python?

后端 未结 8 1715
庸人自扰
庸人自扰 2020-12-12 16:25

I\'d interacting with a lot of deeply nested json I didn\'t write, and would like to make my python script more \'forgiving\' to invalid input. I find myself writing involve

8条回答
  •  没有蜡笔的小新
    2020-12-12 16:38

    You could use a defaultdict and the context manager approach as outlined in Raymond Hettinger's PyCon 2013 presentation

    from collections import defaultdict
    from contextlib import contextmanager
    
    @contextmanager
    def ignored(*exceptions):
      try:
        yield
      except exceptions:
        pass 
    
    item = defaultdict(str)
    
    obj = dict()
    with ignored(Exception):
      item['a'] = obj.get(2).get(3) 
    
    print item['a']
    
    obj[2] = dict()
    obj[2][3] = 4
    
    with ignored(Exception):
      item['a'] = obj.get(2).get(3) 
    
    print item['a']
    

提交回复
热议问题