迭代方法 - Python

时间:2015-04-24 16:40:44

标签: python multithreading methods parallel-processing threadpool

我在班级Domain中创建了以下线程实用程序:

def __run_threads(self, targets):
        with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
            future_job = { executor.submit(target): target for target in targets }
            for future in concurrent.futures.as_completed(future_job):
                try:
                    data = future.result()
                except Exception as exc:
                    self.log.exception(exc)
                else:
                    self.log.info("Data: %s" % data)

就是这样,我可能想要terminateinitiate属于我的班级Domain的节点。为了使其尽可能通用,我想传递一个targets列表,一个要执行的target数组:

targets = [ node.terminate_instance for node in self.nodes ]

targets = [ node.start_instance for node in new_nodes ]
self.__run_threads(targets)

然而,当我执行我得到的功能时:

test_domain.py", line 19, in test_constructor
    dobj = domain.Domain(name="test_domain", cluster_size=1)
  File "domain.py", line 31, in __init__
    self.__run_threads(om_node.start_instance)
  File "domain.py", line 71, in __run_threads
    future_job = { executor.submit(target): target for target in targets }
TypeError: 'instancemethod' object is not iterable

如何迭代Python中的方法列表?

1 个答案:

答案 0 :(得分:1)

追溯显示您正在执行此操作:

self.__run_threads(om_node.start_instance)

因此,您将单个方法实例传递给__run_threads,而不是实例方法列表,这是方法所期望的(以及您甚至明确声明要传递给它的内容)。您只需要让调用者传递一个列表:

self.__run_threads([om_node.start_instance]) # Or a list comprehension that provides multiple instance methods, like in your examples.