[IronPython] How to dynamically define and call a function?

Vagmi Mudumbai vagmi.mudumbai at gmail.com
Mon Sep 18 11:50:42 CEST 2006


Alternatively, you can simply use the file object to write it to a new
module and import it later.

newmod=file('newmodule.py','w')
newmod.write('def add(x,y):\n    return x+y\n')
newmod.close()
import newmodule
print newmodule.add(10,20)

Vagmi

On 9/18/06, Sanghyeon Seo <sanxiyn at gmail.com> wrote:
>
> 2006/9/18, Gary Stephenson <garys at ihug.com.au>:
> > I started off trying to use standard "compile()" function and "exec"
> > statement, but was unable to make it work, although I'm sure there must
> be a
> > way. Is there? How?
>
> This works for me:
>
> IronPython 1.0.2449 on .NET 2.0.50727.42
> Copyright (c) Microsoft Corporation. All rights reserved.
> >>> code = "def add(x, y):\n\treturn x + y\n"
> >>> exec code
> >>> add(2, 3)
> 5
>
> Seo Sanghyeon
> _______________________________________________
> users mailing list
> users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
>



-- 
http://geekswithblogs.net/vagmi.mudumbai
http://installneo.blogspot.com

"Peace is its own reward." - Mahatma Gandhi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20060918/8ca47cf7/attachment.html>


More information about the Ironpython-users mailing list