2017-04-05 166 views
1

我有一種方法可以檢索kwargs和未來。 我想將kwargs的字典保存到將來,以便以後用kwargs處理未來的結果。使用kwargs作爲字典中的鍵

class ThreadPoolExecutorImproved(object): 

def __init__(self, max_workers): 
    self._executor = ThreadPoolExecutor(max_workers) 
    self._futures = {} 

def __enter__(self): 
    return self 

def __exit__(self, exc_type, exc_val, exc_tb): 
    kwargs_to_exception = {} 
    for kwargs, future in self._futures.iteritems(): 
     if future.exception(): 
      kwargs_to_exception[kwargs] = future.exception 

    if kwargs_to_exception: 
     raise ThreadPoolException(kwargs_to_exception) 

def submit(self, fn, *args, **kwargs): 
    future = self._executor.submit(fn, *args, **kwargs) 
    key = tuple(kwargs.items()) 
    self._futures[key] = future 
    return future 

但是,我得到一個錯誤就行了self.futures[key] = future

TypeError: unhashable type: 'dict' for python 

爲什麼呢?我從kwargs創建了一個元組!

+2

這意味着你有** **字典在一個'kwargs'的**值**。 –

+0

我明白了。所以我需要每個值都包含一個元組? – Dejell

+0

你確實可以將每個字典轉換爲一個元組的等價物。請注意,您將不得不以遞歸方式**這樣做,因爲這些字典也可以包含字典等。 –

回答

1

這種情況的典型解決方法是使用future作爲重點; 您的代碼

key = tuple(kwargs.items()) 
self._futures[key] = future 

遷移到

self._futures[future] = tuple(kwargs.items()) 

而且當你要處理self._futures,你可以遍歷這個

for future, kw in self._futures: 
    # check kw 
    # do your stuff