为什么 multiprocessing 中的 Pool class 缺少 Python 2 中的 __exit__() 方法?

Why the Pool class in multiprocessing lack the __exit__() method in Python 2?

我不清楚为什么 Python 2.7 implementation of Pool does not have the __exit__() method that is present in the Python 3 version 与 class 相同。添加 __exit__() 方法(当然还有 __enter__() )是否安全(我只想使用 with Pool(n) as p: )或者是否有特殊原因避免它?

似乎没有任何理由避免它。查看它并快速测试它并没有带来任何奇怪的行为。这是在 Issue 15064 中实现的,它似乎没有在 2.7 中添加(可能是因为只考虑了错误修复)。

__enter__ 返回 self 并从 __exit__ 调用 terminate 应该是在 Python 3.3 中实现的方法。不过,不要改变源代码(if 那是你的意图),只需创建一个自定义子类:

from multiprocessing.pool import Pool as PoolCls

class CMPool(PoolCls):
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        return self.terminate()