Check for instance of Python multiprocessing.Connection?

自古美人都是妖i 提交于 2019-12-24 03:21:03

问题


Connection objects are created when opening a multiprocessing.Pipe. However, it's not clear how to check whether an object is an instance of a Connection.

In Python3 (3.4, 3.3, !3.2), to detect an instance of Connection I can do:

from multiprocessing.connection import Connection

if isinstance(f, Connection):
  print("f is a Connection to a Pipe")

from multiprocessing.dummy.connection import Connection also works on all Python3, but not Python2.

However, this results in an ImportError using Python2. How am I supposed to reliably check for a Connection object?


回答1:


There are significant implementation differences between Python 2 and 3 w. r. t. multiprocessing Connection objects. In Python 2, you can import them via:

from _multiprocessing import Connection

In Python 2, the Connection class is implemented in a helper module _multiprocessing, written in C (source here). I think it is written in C for better accessibility of the Windows API and possibly for performance reasons. I assume that in case of Python 3 the special Windows API calls required for implementing named pipes have been externalized to the winapi module.

You can easily, depending on the Python version, either import Connection from multiprocessing.connection or from _multiprocessing so that your code runs on both, Python 2 and 3.




回答2:


Assuming the other things that your object might be are rather different from a Connection, you can do something like:

if hasattr(f, 'recv'):
     print("f can be received from")

This will be portable without having to import the private class in Python 2.



来源:https://stackoverflow.com/questions/28549738/check-for-instance-of-python-multiprocessing-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!