Editing a function in-memory and in-place

S

Sori Schwimmer

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top