[Tutor] Comparative code questions: Python vs. Rebol

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue Jan 14 19:54:02 2003


> > Dynamically compose a series of functions such that
> > # python
> >   print H3("This an html header of level 3")
> >   >>> "<H3>This is an html header of level 3</H3>"
> >
> > In rebol, it works this way:
> > repeat count 6[
> >     do rejoin[ "H" count ": sub[val][val: reduce val ml[H" count "[(val)]]]" ]
> >     ]
> >
> > Is it possible to do this in python? If so, an example would
> > be appreciated.
>
> Here's my first shot:
>
> >>> for i in range(1,7):
> ...   exec ("def H%d(txt): return '<H%d>' + txt + '</H%d>'" % (i,i,i))
> ...
> >>> H3("foo")
> '<H3>foo</H3>'

Hi John and Tim,

This works well.  If we have an allergy against eval(), we can still
fiddle around with namespaces to get a similar effect.  Every module has
its own "global" namespace that contains every global variable we use:

###
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__':
'__main__', '__doc__': None}
>>> a = 42
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__':
'__main__', '__doc__': None, 'a': 42}
###


It turns out to be a writable dictionary, so if we really want to abuse
the language, here's one way to do it.  *grin* We can define those six
HEADER functions using a loop as well as some use of inner functions:

###
>>> def make_new_header_function(i):
...     def new_function(s):
...         return '<H%s>%s</H%s>' % (i, s, i)
...     return new_function
...
>>> for i in range(1, 6+1):
...     globals()['H%s' % i] = make_new_header_function(i)
...
>>> H3('hello')
'<H3>hello</H3>'
>>> H1, H2, H3
(<function new_function at 0x8154d14>,
 <function new_function at 0x8157204>,
 <function new_function at 0x81573b4>)
###


Hope this helps!