Defining new functions at runtime

Ken Seehof kseehof at neuralintegrator.com
Wed May 1 14:08:32 EDT 2002


>     I am writing a GUI interface to a database using tkinter.
> Now, I want to
> provide a facility where a user can define python functions using the GUI
> and then run them in the same runtime environment. so, a normal function
> needs to be treated like a method object.
>    Is this possible? Can I treat functions as first class objects? Can
> somebody please guide me as to how I could accomplish this?
>
> Thanks
> Chandan

Functions are first class objects in python.  Actually just about everything
in python is a first class object.  (If a mutant topic branches off of this
talking about things like 'if' and 'for' not being objects (they are in some
languages), please change the subject heading :-) so we don't confuse
anyone.)

The easiest way to do what you want is to just use eval and exec.

You can get clever and use lambda with eval:

>>> s = "x*2+1"
>>> d = {'x': 5}
>>> eval(s, d)
11
>>> f = lambda x: eval(s, {'x':x})
>>> f(3)
7

... or if you want the user to type in function definitions:

>>> d = {}
>>> s = '''
... def foo(bar):
...    print 'bar =',bar
...    return bar+5
... '''

>>> exec s in d
>>> d['foo']
>>> <function foo at 0x017EC140>
>>> d['foo'](4)
bar = 4
9

Note the difference beween exec and eval: eval evaluates a string
as an expression and returns the result; exec executes a string of
arbitrary python code and doesn't return anything.  They both use
a dictionary to represent the context in which the python string
is interpreted (that's how 'foo' got into the d dictionary).

Alternatively, you can use the 'new' module, which gives you tools
to create all kinds of things like modules, classes, functions and
methods, that are identical to the objects normally created by the
python interpreter.  I haven't tried it, but it looks a bit more
complicated than what I've described above, and the documentation
doesn't make it obvious how to create a 'code' object (which is a
prerequisite to using new.function.  The 'new' module is a wrapper
for the low level C code that implements these kinds of python
objects.

Keep in mind that there can be security issues associated with this
kind of thing.  For example, if your application is a web application,
people can make your application run arbitrary python code that emails
data, destroys files, downloads and runs trojan horses, etc.  There
are ways to protect yourself, but that's another topic that might not
apply to you right now.

I hope this points you in the right direction.

Enjoy,

- Ken Seehof
kseehof at neuralintegrator.com







More information about the Python-list mailing list