can i define a new method at runtime?

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Fri Jun 18 23:30:22 CEST 2004


Raoul wrote:

> If my control myTextBox has a change() event for on change and I want
> to make it verify the input is an integer I could do...
> 
> def myTextBox.change():
>    verifyInteger(myTextBox.Value)
> 
> def verifyInteger(x):
>    try:
>       string.atoi(x.value)
>    except ValueError :
>       message(x," needs to be an integer")
>       x.setFocus()
> 
> but i have literally hundreds of these things to do....
> 
> I'd like to be able to say somethign like
> 
> myTextBox.change = lambda x : verifyInteger(x)
> 
> so when i initialize my form i'd like to run through a list that looks
> like
> 
> [["controlName1","verifyInteger"],["controlName2,"verifyFloat"],["controlName3
> "verifyInteger"]

I'm not a guru, so expect this solution to be bloated ;)

For example, (ab)use a class to build a unit with all the verify-functions:

class Verify(object):
	def verify_integer(x): [...]
	def verify_float(x):   [...]

# Then, iterate over the list:

for pair in list: # list being your example above
	control = getattr(__main__, pair[0])
	control.changed = eval("lambda self: Verify." + pair[1] + "(self.Value)")
# for this line there MUST be a solution without eval but I don't see it
at the moment

BTW, you should use tuples if the information about the handling
functions is static.

regards, Reinhold

-- 
Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
mitbrächte, wäre das bedauerlich.  Was bei Windows der Umfang eines
"kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
  -- David Kastrup in de.comp.os.unix.linux.misc



More information about the Python-list mailing list