Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


Java/Open Source Daily

jobs.webdeveloper.com

e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


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


Up to => Home / Authoring / Tutorials / Python




Jupiter Online Media: internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and Jupiter Online Media

Jupitermedia Corporate Info


Legal Notices, Licensing, & Permissions, Privacy Policy.

Web Hosting | Newsletters | Tech Jobs | Shopping | E-mail Offers