1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#
# This module shows how to use arbitrary callables with a subclass of
# `BaseManager`.
#
from multiprocess import freeze_support as freezeSupport
from multiprocess.managers import BaseManager, IteratorProxy as BaseProxy
##
class Foo(object):
def f(self):
print('you called Foo.f()')
def g(self):
print('you called Foo.g()')
def _h(self):
print('you called Foo._h()')
# A simple generator function
def baz():
for i in range(10):
yield i*i
# Proxy type for generator objects
class GeneratorProxy(BaseProxy):
def __iter__(self):
return self
def __next__(self):
return self._callmethod('__next__')
##
class MyManager(BaseManager): pass
# register the Foo class; make all public methods accessible via proxy
MyManager.register('Foo1', Foo)
# register the Foo class; make only `g()` and `_h()` accessible via proxy
MyManager.register('Foo2', Foo, exposed=('g', '_h'))
# register the generator function baz; use `GeneratorProxy` to make proxies
MyManager.register('baz', baz, proxytype=GeneratorProxy)
##
def test():
manager = MyManager()
manager.start()
print('-' * 20)
f1 = manager.Foo1()
f1.f()
f1.g()
assert not hasattr(f1, '_h')
print('-' * 20)
f2 = manager.Foo2()
f2.g()
f2._h()
assert not hasattr(f2, 'f')
print('-' * 20)
it = manager.baz()
for i in it:
print('<%d>' % i, end=' ')
print()
##
if __name__ == '__main__':
freezeSupport()
test()
|