define a new func on the fly?

Bruce Edge bedge at troikanetworks.com
Fri Mar 2 16:37:34 CET 2001


Christopher Li wrote:
> 
> On Thu, 1 Mar 2001, Bruce Edge wrote:
> 
> > >>> class xx:
> > ...   def __init__(self):
> > ...     exec( "def yyy():  print \"yyyyyyyyy\"" )
> > ...
> > >>> x=xx()
> > >>>
> > >>> x.__dict__
> > {}
> >
> > Where is yyy defined?
> In local namespace of __init__.

Ahhh. I'm coming from Tcl, it's a wee bit different.

> >
> > Ideally, I'd like to be able to create it in the global namespace.
> Do yon mean in class xx?
> How about
> 
> >>> class xx:
> ...     def __init__(self):
> ...         exec( "def tmp(self): print 'yyyyyy'")
> ...         self.yyy = tmp
> ...
> >>> x = xx()
> >>> x.__dict__
> {'yyy': <function tmp at 0x81df40c>}

OK, so that kicks it up to the class namespace.
Now, just for completeness, I wanted it in the global namespace, so:

>>> class xx:
...  def __init__(self):
...    global g
...    exec( "def tmp(): print 'yyyyyy'")
...    self.yyy = tmp
...    g = tmp
... 
>>> g=dir  
>>> g
<built-in function dir>

>>> t=xx()
>>> t.__dict__
{'yyy': <function tmp at 0x81e63ec>}
>>> type(g)
<type 'function'>
>>> g()
yyyyyy


Thanks to all for the help. Guess I won't be going back to Tcl after all
:-)

> Chris



More information about the Python-list mailing list