2017-04-05 9 views
1

私はkwargsとfutureを取り出すメソッドを持っています。 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 
関連する問題