define a new func on the fly?

Bruce Edge bedge at troikanetworks.com
Thu Mar 1 20:10:51 EST 2001


Gregory Jorgensen wrote:
> 
> eval() evaluates an expression. exec() executes a statement. Try this:

Yup, that was it! thanks!

Now, how can I get it to create this function in the global namespace?
I'm doing this inside of a class method, so I have no access to the new
func after I leave the class method.

>>> exec( "def xxx():  print \"xxxxxxxx\"" )
>>> xxx()
xxxxxxxx

Woo Hoo! works!

now:

>>> class xx:
...   def __init__(self):
...     exec( "def yyy():  print \"yyyyyyyyy\"" )
... 
>>> x=xx()
>>>     
>>> x.__dict__
{}

Where is yyy defined?

Ideally, I'd like to be able to create it in the global namespace.


-Bruce.

> 
> >>> exec("def f():\n\treturn 'hello'\t")
> >>> f()
> 'hello'
> 
> >>> eval("f()")
> 'hello'
> 
> In article <3A9EE927.8744154E at troikanetworks.com>, Bruce Edge says...
> >
> >I'm trying to define a new function on the at runtime,
> >
> >this fails:
> >
> >>>> eval( "def global_func_name():\n\tpass" )
> >Traceback (most recent call last):
> >  File "<stdin>", line 1, in ?
> >  File "<string>", line 1
> >    def global_func_name():
> >      ^
> >SyntaxError: invalid syntax
> >
> >any idea how I can do this?
> >
> >
> >
> >Thanks, Bruce.
> 
> Greg Jorgensen
> Deschooling Society
> Portland, Oregon, USA
> gregj at pobox.com



More information about the Python-list mailing list