Defining new functions at runtime

holger krekel pyth at devel.trillke.net
Wed May 1 13:02:47 EDT 2002


On Wed, May 01, 2002 at 10:51:34AM -0500, Chandan Shanbhag wrote:
>     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?

Functions *are* first class objects. What makes you think otherwise?

If you have *no security concerns whatsoever* use this pattern:

    src = """
    def f(arg):
        print arg
    """

    exec src 


src contains the function definition (which you might
want to make up from your GUI-input).

exec allows to execute this function definition
in the current scope. After which you can
have the function 'f' available and use
it like usual:

    f("hello world")

BUT BE AWARE:

- 'execing' like this may ruin your complete
  program because it takes place right inside
  your program's scope. It's almost always better to
  say 

    exec src in dict1,dict2

  where dict1 is the dictionary containing the
  global bindings and dict2 the on containing
  the local bindings. A binding is a
  'name': object - mapping. You can transfer
  bindings from your program's scope into
  dict1 or dict2!

- you should follow Boudewijn's link (same thread)
  to get deeper knowledge.

- you should use a try/except class and pass
  the error to the user. otherwise
  your program may prematurely end.
 

regards,

    holger





More information about the Python-list mailing list