1

I try to define a function with a variable name.

Names are retrieved from a database. For every name I want to define a button and have separate handling:

title=['BNL','CE']
for i in range(0,len(title)):
    panelvpu.add(Button(title[i]))


for i in range(0,len(title)):
    eval('def onButtonClick'+title[i]+'(self, event):')
    eval('    Window.alert("Yes")')

The button definition is ok, but the handling of the event in the defined function gives an error

im1 SyntaxError: at index 4 in "def onMenu1Item1(self): 
Window.alert("Item 1 selected")": expected ';', got 'onMenu1Item1'

After feedback I changed this to

    title=['BNL','CE']
    for t in title : panelvpu.add(Button(t))

for t in title:        
    def_code = "print t"
    exec(def_code)

Just to get the feeling; under python this works fine. But I use pyjamas and the last code does rais the error stating

 im1 TypeError: iter is undefined

It appears that pyjamas is not supporting eval() and exec() yet.

Richard

Richard
  • 135
  • 2
  • 10
  • That doesn't look like separate handling to me... – Ignacio Vazquez-Abrams Oct 07 '11 at 18:38
  • 1
    Looks like you're trying to make a function factory for callback commands; good thought, but there are better tools that Python gives you to do this. – Thomas Oct 07 '11 at 18:44
  • What is a Button? How is the event handler associated with the Button? It looks like you're trying to write a free function, but expecting it to behave like a method that belongs to the Button instance. – Karl Knechtel Oct 07 '11 at 19:12

1 Answers1

9

There are a number of problems here:

1) eval is for evaluating an expression, not executing statements.

2) exec would need the entire function in one exec, not split onto separate lines as you have it.

3) There are much easier ways to create functions, depending on what you want to have in the body. Tell us about what you really want to do.

4) Your loop is much simpler as: for t in title: blah blah t.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662