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創建了一個元組!
這意味着你有** **字典在一個'kwargs'的**值**。 –
我明白了。所以我需要每個值都包含一個元組? – Dejell
你確實可以將每個字典轉換爲一個元組的等價物。請注意,您將不得不以遞歸方式**這樣做,因爲這些字典也可以包含字典等。 –