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