473,387 Members | 1,693 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

can i define a new method at runtime?

I have a GUI application where I want to assign validation methods to
controls.

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"]

but i can't seem to make this work.

I've tried to use exec("def foo = lambda x: do something....")

but that doesn't seem to work....

Got any ideas ???
Jul 18 '05 #1
6 1580
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
Jul 18 '05 #2
>>>>> "Raoul" == Raoul <ra******@yahoo.com> writes:

Raoul> I have a GUI application where I want to assign validation
Raoul> methods to controls.

Raoul> If my control myTextBox has a change() event for on change
Raoul> and I want to make it verify the input is an integer I
Raoul> could do...

If there is a change method, I assume you need to implement the class
yourself. Why not just subclass the root TextBox class and create a
IntegerTextBox class that has verifyInteger in the change method? Then
you just choose at instantiation time that this particular textbox
needs an integer...

--
Ville Vainio http://tinyurl.com/2prnb
Jul 18 '05 #3
You are close. Try something like

def verifyInteger(x):
try:
string.atoi(x.value)
except ValueError :
message(x," needs to be an integer")
x.setFocus()

In a dictionary put keys (controlNames) and
pointers to what function (or method) to call
for that controlName.

verifiers={'controlName1': verifyInteger,
'controlName2': verifyFloat,
...
'controlNameN': veryfySomething}
In your program call the function from the
dictionary as follows:

verifiers['controlName1'](x)
verifiers['controlName2'](x)
....

This works because the result of the getting
verifiers[controlName] is a pointer to a
function instead of a value. This pointer
has a call method, so you can just put the
arguments after it.

HTH,
Larry Bates
Syscon, Inc.

"Raoul" <ra******@yahoo.com> wrote in message
news:7b**************************@posting.google.c om...
I have a GUI application where I want to assign validation methods to
controls.

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"],["controlNam
e3 "verifyInteger"]

but i can't seem to make this work.

I've tried to use exec("def foo = lambda x: do something....")

but that doesn't seem to work....

Got any ideas ???

Jul 18 '05 #4
ra******@yahoo.com (Raoul) wrote:

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"]


def change_Integer(self):
try:
string.atoi(self.value)
except ValueError:
message(...)
self.setFocous()
def change_Currrency(self):
...

dict = {"box1": "Integer", "box2": "Currency"}

import new
for (box_name, box_type) in dict.iteritems():
function_name = 'change_%s' % box_type
f = eval(function_name)
box = getattr(myFrame, box_name)
box.change = new.instancemethod(f, box, box.__class__)

replace eval() by globals() if safety is a concern, or replace by
getattr(...) if functions are defined in modules or classes. (.im_func
maybe needed, anyway, you'll figure out the specifics on your own.)

Hung Jung
Jul 18 '05 #5
Ville Vainio <vi***@spammers.com> wrote:
If there is a change method, I assume you need to implement the class
yourself. Why not just subclass the root TextBox class and create a
IntegerTextBox class that has verifyInteger in the change method? Then
you just choose at instantiation time that this particular textbox
needs an integer...


This is OK if there are only a few types of boxes. But entry data
types are features, and they tend to grow and become complicated, even
if Regex (regular expression) patterns were used. Besides, the
verification logic is a conceptual unit on its own right, so according
to the AOP (aspect-oriented programming) philosophy, it's best to
group the verification methods together in some "aspect class". There
may be new dimensions to the problem that one may not have foreseen at
the time of design. For instance, localization (currency, dates, usage
of commas and periods, ZIP codes, etc.) Having verification code in
its own hierarchy allows you to make changes more easily and take
advantage of class inheritance for code re-use. Once you have the
verification logic done, you hook it to the widget objects somehow. In
Python, this usually involves some form of metaprogramming. There are
too many ways to do it, and you'll probably not find two people doing
it the same way. Some tools in the arsenal are: using
functions/methods as first class objects and assign them or tweak them
to your heart's content, using the "new" module, using code objects
and "exec" statements, tweaking an existing object's __class__
attribute, implementing/overriding the __getattr__() method in
classes, metaclasses, etc. etc.

regards,

Hung Jung
Jul 18 '05 #6
Something like the untested code below will work, without the need to
"exec" anything.

def verifyInteger(x): ...
def verifyFloat(x): ...
verifiers = {"ControlName1": verifyInteger, "ControlName2": verifyFloat, ....}

class MyTextBox(TextBox):
def __init__(self, controlname, ...):
self.verifyfunc = verifiers[self.controlname]
TextBox.__init__(self, ...)
...
def change(self):
self.verifyfunc(self.value)

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFA1szcJd01MZaTXX0RAizxAJ4lzaIFRv5xeS0+YlD3rK evATT4kACgjbwn
izanXr8+GfuUL9sRfERyi2w=
=12C3
-----END PGP SIGNATURE-----

Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: ZhangZQ | last post by:
if there is a function in a win32 dll, it is definition is int add(int a, int b); how to define that function pointer in C#? thank you very much!
8
by: Pete C | last post by:
In this section of the FAQ: http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.10 an abstract destructor is given a definition with the cryptic comment "It's faster this...
24
by: Jazper | last post by:
hi i have this problem. i made a class deverted by CRootItem with implementation of IDisposable-Interface. i made a test-funktion to test my Dispose-Method.... but when set a breakpoint in my...
8
by: AngryGerbil | last post by:
hey, How do I acquire MethodInfo WITHOUT hardcoding method name as a string?!??!The fact I have to use xxx.Gettype.GetMethod("MyMethod", xxx) is making me want to drive an ice pick into my eye! I...
0
by: dpp | last post by:
Hi I am calling a method of a .NET component from both win forms and web service applications. Strangly, it is working fine from win forms application, but when i call the same method (same...
2
by: Luis Arvayo | last post by:
I am compiling and executing c# code at runtime and I need to define in CompilerParameters.ReferencedAssemblies one of my own assemblies together with the standard System.dll u others. Example:...
20
by: subramanian100in | last post by:
Suppose I have #included <stdint.h> #define MAX_LINE_SIZE SIZE_MAX or const size_t maxLineLength = SIZE_MAX ; Between the above #define and const declaration, which should be...
1
by: Kenneth McDonald | last post by:
I can see an obvious but hacky way to define a Python function at runtime. I can't see any obvious way to add a method to a class at runtime (though I'm sure one could do just about anything by...
5
by: alan | last post by:
Hello world, I'm wondering if it's possible to implement some sort of class/object that can perform mapping from class types to strings? I will know the class type at compile time, like so:...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.