Check for instance of Python multiprocessing.Conne

2019-07-23 07:33发布

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?

2条回答
迷人小祖宗
2楼-- · 2019-07-23 07:52

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-23 08:10

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.

查看更多
登录 后发表回答