Examples¶
Retrying¶
classClient(object):def__init__(self,address):self.address=addressself.connect()defconnect(self):# establish connectiondefaction(self,data):# do some stuff
Now patch theClient class to have the retry functionality on all its methods:
aspectlib.weave(Client,aspectlib.contrib.retry())
or with different retry options (reconnect before retry):
aspectlib.weave(Client,aspectlib.contrib.retry(prepare=lambdaself,*_:self.connect())
or just for one method:
aspectlib.weave(Client.action,aspectlib.contrib.retry())
You can see here the advantage of having reusable retry functionality. Also, the retry handling isdecoupled from theClient class.
Debugging¶
… those damn sockets:
>>>importaspectlib,socket,sys>>>withaspectlib.weave(...socket.socket,...aspectlib.debug.log(...print_to=sys.stdout,...stacktrace=None,...),...lazy=True,...):...s=socket.socket()...s.connect(('example.com',80))...s.send(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')...s.recv(8)...s.close()...{socket...}.connect(('example.com', 80)){socket...}.connect => None{socket...}.send(...'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n'){socket...}.send => 3737{socket...}.recv(8){socket...}.recv => ...HTTP/1.1......'HTTP/1.1'...
The output looks a bit funky because it is written to be run bydoctest - so you don’t use broken examples :)
Testing¶
Mock behavior for tests:
classMyTestCase(unittest.TestCase):deftest_stuff(self):@aspectlib.Aspectdefmock_stuff(self,value):ifvalue=='special':yieldaspectlib.Return('mocked-result')else:yieldaspectlib.Proceedwithaspectlib.weave(foo.Bar.stuff,mock_stuff):obj=foo.Bar()self.assertEqual(obj.stuff('special'),'mocked-result')
Profiling¶
There’s no decorator for such in aspectlib but you can use any of the many choices onPyPI.
Here’s one example withprofilestats:
>>>importos,sys,aspectlib,profilestats>>>withaspectlib.weave('os.path.join',profilestats.profile(print_stats=10,dump_stats=True)):...print("os.path.join will be run with a profiler:")...os.path.join('a','b')...os.path.join will be run with a profiler: ... function calls in ... seconds... Ordered by: cumulative time... ncalls tottime percall cumtime percall filename:lineno(function) ... 0.000 0.000 0.000 0.000 ... ... 0.000 0.000 0.000 0.000 ... ... 0.000 0.000 0.000 0.000 ... ... 0.000 0.000 0.000 0.000 .........'a...b'
You can even mix it with theaspectlib.debug.log aspect:
>>>importaspectlib.debug>>>withaspectlib.weave('os.path.join',[profilestats.profile(print_stats=10,dump_stats=True),aspectlib.debug.log(print_to=sys.stdout)]):...print("os.path.join will be run with a profiler and aspectlib.debug.log:")...os.path.join('a','b')...os.path.join will be run with a profiler and aspectlib.debug.log:join('a', 'b') <<< ... ... function calls in ... seconds... Ordered by: cumulative time... ncalls tottime percall cumtime percall filename:lineno(function) ... 0.000 0.000 0.000 0.000 ... ... 0.000 0.000 0.000 0.000 ... ... 0.000 0.000 0.000 0.000 ... ... 0.000 0.000 0.000 0.000 .........'a/b'
