Editing a function in-memory and in-place

Sori Schwimmer sxn02 at yahoo.com
Thu Apr 27 13:09:14 EDT 2006


Generate your function as a string. Be careful to
indent correctly and append \n at line's end. Then
execute the string with exec(name_of_string). Then
edit your string as necessary, and execute again.

An example follows, directly from one of my projects:

        # create a "function" to apply on prtbl
        if d1[j][3]==';': # if value >
          prfunc=('l_vl=0\nfor l_i in range(%s):\n if
l_vl>%s:' % (len(prtbl),lowm))
        elif lowm>0.0:
          prfunc=('for l_i in range(%s' % lowm)
          if hiwm>0.0:
            prfunc+=(',%s):' % hiwm)
          else:
            prfunc+=(',%s):' % len(prtbl))
        else:
          prfunc=('for l_i in range(%s):' %
len(prtbl))
        if d1[j][4]=='-':
          prfunc+='\n  prtbl[l_i]=prtbl[l_i-1]'
        if d1[j][1]=='$' and d1[j][2]==chr(255):
          prfunc+=('\n  prtbl[l_i]=%s' % dsz)
        elif d1[j][1]=='$':
          prfunc+=('\n  prtbl[l_i]=prtbl[l_i-1]-%s' %
dsz)
        elif d1[j][1]=='%':
          prfunc+=('\n  prtbl[l_i]*=(1-%s/100)' % dsz)
        if d1[j][3]==';': # if value >
          prfunc+='\n l_vl+=prtbl[l_i]'
        #print prfunc
        #print prtbl
        exec(prfunc)

Hope it helps,
Sorin Schwimmer

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 



More information about the Python-list mailing list