1# 2# This module shows how to use arbitrary callables with a subclass of 3# `BaseManager`. 4# 5# Copyright (c) 2006-2008, R Oudkerk 6# All rights reserved. 7# 8 9from multiprocessing import freeze_support 10from multiprocessing.managers import BaseManager, BaseProxy 11import operator 12 13## 14 15class Foo(object): 16 def f(self): 17 print 'you called Foo.f()' 18 def g(self): 19 print 'you called Foo.g()' 20 def _h(self): 21 print 'you called Foo._h()' 22 23# A simple generator function 24def baz(): 25 for i in xrange(10): 26 yield i*i 27 28# Proxy type for generator objects 29class GeneratorProxy(BaseProxy): 30 _exposed_ = ('next', '__next__') 31 def __iter__(self): 32 return self 33 def next(self): 34 return self._callmethod('next') 35 def __next__(self): 36 return self._callmethod('__next__') 37 38# Function to return the operator module 39def get_operator_module(): 40 return operator 41 42## 43 44class MyManager(BaseManager): 45 pass 46 47# register the Foo class; make `f()` and `g()` accessible via proxy 48MyManager.register('Foo1', Foo) 49 50# register the Foo class; make `g()` and `_h()` accessible via proxy 51MyManager.register('Foo2', Foo, exposed=('g', '_h')) 52 53# register the generator function baz; use `GeneratorProxy` to make proxies 54MyManager.register('baz', baz, proxytype=GeneratorProxy) 55 56# register get_operator_module(); make public functions accessible via proxy 57MyManager.register('operator', get_operator_module) 58 59## 60 61def test(): 62 manager = MyManager() 63 manager.start() 64 65 print '-' * 20 66 67 f1 = manager.Foo1() 68 f1.f() 69 f1.g() 70 assert not hasattr(f1, '_h') 71 assert sorted(f1._exposed_) == sorted(['f', 'g']) 72 73 print '-' * 20 74 75 f2 = manager.Foo2() 76 f2.g() 77 f2._h() 78 assert not hasattr(f2, 'f') 79 assert sorted(f2._exposed_) == sorted(['g', '_h']) 80 81 print '-' * 20 82 83 it = manager.baz() 84 for i in it: 85 print '<%d>' % i, 86 print 87 88 print '-' * 20 89 90 op = manager.operator() 91 print 'op.add(23, 45) =', op.add(23, 45) 92 print 'op.pow(2, 94) =', op.pow(2, 94) 93 print 'op.getslice(range(10), 2, 6) =', op.getslice(range(10), 2, 6) 94 print 'op.repeat(range(5), 3) =', op.repeat(range(5), 3) 95 print 'op._exposed_ =', op._exposed_ 96 97## 98 99if __name__ == '__main__': 100 freeze_support() 101 test() 102