Exec Statement Question
Victor Subervi
victorsubervi at gmail.com
Mon Nov 30 06:23:59 EST 2009
On Sun, Nov 29, 2009 at 10:23 PM, Dave Angel <davea at ieee.org> wrote:
> exec is a statement, and statements don't have "return values." It's not
> a function, so there are no parentheses in its syntax, either. exec is also
> a technique of last resort; there's nearly always a better/safer/faster way
> to accomplish what you might want, but of course you don't say what that is.
>
> As for "returning" values, exec by default uses the same global space as
> your app, so you can just modify a global variable in your "called" code and
> use it afterwards.
>
> abc = 42
> value = 12
> exec "abc = %d" % value
> print abc
>
Taking out the parenthesis did it! Thanks. Now, you state this is an option
of last resort. Although this does indeed achieve my desired aim, here is a
complete example of what I am trying to achieve. The following is from
'createTables2.py':
for table in tables:
try:
exec 'from options import %s' % table
except:
pass
try:
exec '%s()' % table
except:
pass
The following is from 'options.py':
def jewelry(which=''):
code = []
names = []
meanings = []
code.append(['5', '5½', '6', '6½', '7', '7½', '8',
'8½', '9', '9½', '10', '10½', '11', '11½', '12',
'12½', '13', '13½'])
meanings.append('The standard ring sizes.')
names.append('ringSizes')
code.append(['Petite (7")', 'Average (7½")', 'Large
(8")', 'Extra-large (8½")'])
meanings.append('The standard bracelet sizes.')
names.append('braceletSizes')
code.append(['16"', '18"', '20"', '22"', '24"'])
meanings.append('The standard necklace sizes.')
names.append('necklaceSizes')
code.append(['14K gold', '18K gold', 'silver', '14K white gold', '18K
white gold', 'platinum', 'tungsten', 'titanium'])
meanings.append('The standard jewelry metals.')
names.append('metals')
code.append(['diamond', 'emerald', 'ruby', 'sapphire', 'pearl', 'opal',
'topaz', 'onyx', 'lapiz lazuli', 'tanzanite', 'garnet', 'quartz', 'rose
quartz', 'amethyst', 'alexandrite', 'peridot', 'tourmaline', 'citrine',
'turquoise'])
meanings.append('The standard jewelry stones.')
names.append('stones')
if which == '':
i = 0
all = ''
while i < len(meanings):
table = '%s\n' % meanings[i]
table += "<table>\n <tr>\n <td colspan='8' align='center'>%s</td>\n
</tr>" % names[i]
j = 0
for elt in code:
if (j + 8) % 8 == 0:
table += ' <tr>\n'
table += ' <td>%s</td>\n' % code[i]
if (j + 8) % 8 == 0:
table += ' </tr>\n'
j += 1
if table[-6:] != '</tr>\n':
table += ' </tr>\n'
table += '</table>\n'
all += table + '<br /><br />'
i += 1
print all
This all works fine; however, if there is a better way of doing it, please
let me know.
Thanks,
V
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091130/bb6e10a1/attachment-0001.html>
More information about the Python-list
mailing list