Intro to Python Introspection and Dynamic Programming
Dynamic Programming
Functional programming, or dynamic programming, is not
exactly the same as introspection, but they are closely
related. Python allows you to assign a another namespace to
a method or procedure, thereby giving you another tool in
program control. Consider this example:
#!/usr/bin/env python
def printones():
print '111111'
def printtwos():
print '222222'
def printtres():
print '33333'
def do_func(which):
# build list of funcs
flist = ['',printones, printtwos, printtres]
flist[which]()
if __name__ == '__main__':
do_func(2)
We insert three methods into a list, then execute one of
the methods depending on the value of the arg -which-
. The parentheses at the end of -
flist[which]()- tell Python that is a callable
function. This should suggest that you could put many
methods in lists, dictionaries, even databases and have
program logic determine which method to call. Therefore,
dynamic programming is actually a form of introspection
because the program is taking action based on its own
content.
An even more powerful method of dynamic programming
follows:
#!/usr/bin/env python
def funca(a,b, op):
str = 'c = a ' + op + ' b'
obj = compile(str,'','exec')
exec obj
print c
if __name__ == '__main__':
funca(6, 3, '*' )
funca(6, 3, '/' )
funca(6, 3, '+' )
funca(6, 3, '-' )
funca(6, 3, '**' )
The compile built-in function creates an object, a
miniature program in the local namespace, which can be
called by exec. Running this program
yields:
18
2
9
3
216
Introspection is a very large topic. This brief
introduction has, I hope, alerted you to the possibilities.
Detailed documentation has been provided on all of the
functions described herein. Most can be found at www.python.org.
The Type Function
Python Introspection
|