Recursive function is the natural way to solve problems when you encounter functional programming. However it is sometimes hard to realize the run-time execution flow even the function is simple. I used to running python debugger and use "commands" to investigate the behavior:
Since I rarely use heavy recursion in Python, I did not feel anything wrong with this approach until seeing an article yesterday. Eli Bendersky uses a decorator to investigate this more effectively. His trick can shows cleaner flow.
This lead to me thinking more possible applications of decorator. We might use decorator to draw callgraph, logging, profiling, unit testing...etc. On the fly!! Simple and beautiful, isn't it? :-)
- (Pdb) l
- 1 -> def iseven(n):
- 2 return True if n == 0 else isodd(n - 1)
- 3
- 4 def isodd(n):
- 5 return False if n == 0 else iseven(n - 1)
- 6
- 7 print(iseven(4))
- [EOF]
- (Pdb) b 2
- Breakpoint 1 at /home/mars/try/python/decorator/use_pdb.py:2
- (Pdb) b 5
- Breakpoint 2 at /home/mars/try/python/decorator/use_pdb.py:5
- (Pdb) commands 1
- (com) p n
- (com) c
- (Pdb) commands 2
- (com) p n
- (com) c
- (Pdb) c
- 4
- > /home/mars/try/python/decorator/use_pdb.py(2)iseven()
- -> return True if n == 0 else isodd(n - 1)
- 3
- > /home/mars/try/python/decorator/use_pdb.py(5)isodd()
- -> return False if n == 0 else iseven(n - 1)
- 2
- > /home/mars/try/python/decorator/use_pdb.py(2)iseven()
- -> return True if n == 0 else isodd(n - 1)
- 1
- > /home/mars/try/python/decorator/use_pdb.py(5)isodd()
- -> return False if n == 0 else iseven(n - 1)
- 0
- > /home/mars/try/python/decorator/use_pdb.py(2)iseven()
- -> return True if n == 0 else isodd(n - 1)
- True
- The program finished and will be restarted
- > /home/mars/try/python/decorator/use_pdb.py(1)<module>()
- -> def iseven(n):
- (Pdb)
Since I rarely use heavy recursion in Python, I did not feel anything wrong with this approach until seeing an article yesterday. Eli Bendersky uses a decorator to investigate this more effectively. His trick can shows cleaner flow.
- [~/try/python/decorator] (master) 1410h11m $ python use_trace.py
- iseven(4)
- isodd(3)
- iseven(2)
- isodd(1)
- iseven(0)
- True
- [~/try/python/decorator] (master) 1410h12m $ cat use_trace.py
- from Trace import TraceCalls
- @TraceCalls()
- def iseven(n):
- return True if n == 0 else isodd(n - 1)
- @TraceCalls()
- def isodd(n):
- return False if n == 0 else iseven(n - 1)
- print(iseven(4))
This lead to me thinking more possible applications of decorator. We might use decorator to draw callgraph, logging, profiling, unit testing...etc. On the fly!! Simple and beautiful, isn't it? :-)
留言
張貼留言