2017-02-23 75 views
2

我試圖趕上使用decorator異常的cached_propertyhttps://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76與cached_property捕獲異常

https://pypi.python.org/pypi/cached-property

我願做如下簡單的東西,但是這並不工作

from pprint import pprint 
import time 
from cached_property import cached_property 

class MyException(Exception): 
    pass 

def catch_my_exceptions(fn): 
    def wrapped(*args, **kwargs): 
     try: 
      return fn(*args, **kwargs) 
     except MyException as e: 
      cls = args[0] 
      err = 'Found error at {}: {}'.format(time.asctime(), e) 
      cls.error_msgs.append(err) 
      print(err) 
      return 
    return wrapped 

class Foo(object): 
    def __init__(self): 
     self.vars = {} 

    @cached_property 
    @catch_my_exceptions 
    def is_cache_working(self): 
     self.vars[time.asctime()] = True 
     time.sleep(3) 
     print('running cache runner') 
     return time.asctime() 

fo = Foo() 
for i in range(3): 
    print(fo.is_cache_working) 
    pprint(fo.vars) 


# This doesn't trigger caching 

running cache runner 
Thu Feb 23 21:45:15 2017 
{'Thu Feb 23 21:45:11 2017': True} 
running cache runner 
Thu Feb 23 21:45:18 2017 
{'Thu Feb 23 21:45:11 2017': True, 'Thu Feb 23 21:45:15 2017': True} 
running cache runner 
Thu Feb 23 21:45:21 2017 
{'Thu Feb 23 21:45:11 2017': True, 
'Thu Feb 23 21:45:15 2017': True, 
'Thu Feb 23 21:45:18 2017': True} 



# Current solution that works: 

我的這一切是做以下事情。有人可以建議我一個更好的方法。還我怎麼會傳例外列表這個my_cached_decorator

import time 
from pprint import pprint 
from cached_property import cached_property 

class MyException(Exception): 
    pass 

class my_cached_property(cached_property): 
    def __init__(self, func): 
     super(self.__class__, self).__init__(func) 

    def __get__(self, obj, cls): 
     try: 
      super(self.__class__, self).__get__(obj, cls) 
     except MyException as e: 
      err = 'Found error at {}: {}'.format(time.asctime(), e) 
      print(err) 
      value = obj.__dict__[self.func.__name__] = None 
      return value 

class Foo(object): 
    def __init__(self): 
     self.vars = {} 

    @my_cached_property 
    def is_cache_working(self): 
     self.vars[time.asctime()] = True 
     time.sleep(3) 
     print('running cache runner') 
     raise MyException('fooobar') 
     return time.asctime() 

fo = Foo() 
for i in range(3): 
    print(fo.is_cache_working) 
    pprint(fo.vars) 

回答

0

它可能不是最好的解決辦法,但你將有機會獲得內部功能從裝飾到主叫方返回,還從裝飾的閉包內。

例子:

def decorator(f): 
    def wrapper(*args, **kwargs): 
     try: 
      f(*args, **kwargs) 
     except Exception as e: 
      wrapper.__dict__.setdefault('errors', []).append(e) 
    return wrapper 

@decorator 
def raiser(): 
    raise Exception('Oh no!') 

> raiser() 
> raiser.errors 
[Exception('Oh no!')] 
0

好吧,我想通了這個問題,它是在方式cached_property作品。爲了緩存它,它會將該值寫入實例,並使用與其封裝的函數相同的名稱。問題在於它包裝的函數的名稱的名稱爲「包裝」,來自裝飾器。所以,如果你在初始的fo.is_cache_working之後訪問過fo.wrapped,你會得到你的緩存結果。

沒有簡單的方法將兩個想法混合在一起。最簡單的解決方案是編寫自己的cached_property,它自己存儲該值:

class cached_property(object): 
    def __init__(self, func): 
     self.func = func 
     # you can store other function attributes here - such as __doc__ - if you want 
     self.values = {} 

    def __get__(self, instance, owner): 
     if instance in self.values: 
      return self.values[instance] 
     else: 
      value = self.values[instance] = self.func(instance) 
      return value