0

Working:

import multiprocessing
from time import sleep

class bar():
    def __init__(self): pass

    def x(self, a, b): print(self, a, b)

    def y(self, a, b=None, c=None): print(self, c, b, a)

def phandler(ops):
    hbar = bar()
    while True:
        fname, args, kwargs = ops.get()
        fn = eval("hbar." + fname)
        fn(*args, **kwargs)

def x(*args, **kwargs): ops.put(["x", args, kwargs])

def y(*args, **kwargs): ops.put(["y", args, kwargs])

if __name__ == "__main__":
    ops = multiprocessing.Manager().Queue()
    multiprocessing.Process(target=phandler, args=(ops,)).start()
    x(1, 2)
    y(1, c=2)
    sleep(1)  # or any other way to wait for the functions to finish execution

Disadvantage: Needs one function in the main context per function in the foreign class in the other process.

As you can see, the code of x() and y() in the main context is almost identical. Doesn't that call for some optimization? What I'm thinking about is kind of a "dispatcher" function, that can be called under different names, kind of like this:

def dispatch(*args, **kwargs): ops.put([__name__, args, kwargs])
x = y = dispatch

But my research so far ran into 2 basic issues:

  1. Yes, name does not work (it's just a placeholder) but I couldn't find any other method that returns "x" or "y" and not always just "dispatch", as well.

  2. Instead of defining multiple functions I now need to define multiple aliases for the dispatcher function, which is sub-optimum, as well.

Any ideas to have this working in the most general way?

1
  • please add an appropriate language tag
    – cyberbrain
    Commented Jul 4 at 16:56

0

Browse other questions tagged or ask your own question.