我是否误解了Python文档?

huangapple go评论134阅读模式
英文:

Am I misunderstanding the Python documentation?

问题

虽然不是绝对必要的,但我认为拥有一个可以像工作管理器一样使用的多进程队列会很不错。

这是我写的代码:

from multiprocessing import Queue

class WMQueue(Queue):
    def __init__(self):
        super().__init__()
    def __enter__(self):
        return self
    def __exit__(self, *_):
        self.close()

这会引发以下异常:

TypeError: method expected 2 arguments, got 3

原因是multiprocessing.Queue是一个方法。

然而,Queue的文档如下所示:

class multiprocessing.Queue([maxsize])

实际上,Queue方法返回一个multiprocessing.queues.Queue类型的对象,但由于我找不到相关文档,所以可能不安全[尝试]子类化它。

我知道如何重写我的类,以便可以将其用作WM,但这不是重点。如果Queue是一个类,如文档所述,那么我应该能够简单地对其进行子类化。

或者我误解了Python文档吗?

英文:

Although not absolutely necessary, I thought it would be nice to have a multiprocessing Queue that I could use in the style of a Work Manager.

This is what I wrote:

from multiprocessing import Queue

class WMQueue(Queue):
    def __init__(self):
        super().__init__()
    def __enter__(self):
        return self
    def __exit__(self, *_):
        self.close()

This induces the following exception:

TypeError: method expected 2 arguments, got 3

The reason is that multiprocessing.Queue is a method.

However, the documentation for Queue is as follows:

class multiprocessing.Queue([maxsize])

In fact, the Queue method returns an object of type multiprocessing.queues.Queue which, as I can't find any documentation for it, is probably unsafe to [try to] subclass.

I know how I can re-write my class so that it could be used as WM but that's not the point. If Queue was a class, as documented, then I should be able to simply subclass it.

Or am I misunderstanding Python documentation?

答案1

得分: 3

如果您想要继承自某个类,请继承自 multiprocessing.queues.Queue

您是正确的,因为文档并不完全正确,因为 multiprocessing.Queue 实际上是 multiprocessing.context._default_context.Queue 工厂的别名,它在这里定义,并执行以下操作:

def Queue(self, maxsize=0):
    from .queues import Queue
    return Queue(maxsize, ctx=self.get_context())

另外,如果您只想在上下文管理器退出时调用 close() 方法,可以使用 contextlib.closing

q = Queue()
with contextlib.closing(q):
   # ...
英文:

If you want to inherit from something, inherit from multiprocessing.queues.Queue.

You're correct in that the documentation isn't entirely correct, since multiprocessing.Queue is indeed an alias for the multiprocessing.context._default_context.Queue factory that is defined over here and does

    def Queue(self, maxsize=0):
        from .queues import Queue
        return Queue(maxsize, ctx=self.get_context())

As an aside, if all you want to do is call close() on a queue at context manager exit time, use contextlib.closing:

q = Queue()
with contextlib.closing(q):
   # ...

</details>



huangapple
  • 本文由 发表于 2023年3月9日 15:29:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定