Search code examples
pythonmultiprocessingtypecheckingpython-multiprocessing

Check for instance of Python multiprocessing.Connection?


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?


Solution

  • 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.