[Edu-sig] Factory functions: synthesizing top-level names

Andre Roberge andre.roberge at gmail.com
Thu May 27 12:15:38 CEST 2010


On Thu, May 27, 2010 at 2:52 AM, kirby urner <kirby.urner at gmail.com> wrote:

> >
> > Much appreciated André!
>

It was a fun challenge.
 :-)

> >
> > I think our solutions are similar:
> >
>
> ... yours is better though, in that you don't make use of exec.
>
> My use of it was superfluous.
>
> Changing my solution, in light of yours:
>
> #===
>
> def makeroot(N):
>   try:
>       assert type(N)==type(1) and N>=0
>   except:
>       raise ValueError("0 <= N <= integer")
>
>   fname = "root" + str(N)
>
>   if N==0:
>        globals()[fname] = lambda x: pow(x, 0)
>   else:
>       globals()[fname] = lambda x: pow(x, float(1)/N)
>
>
> for i in range(11):
>    makeroot(i)
>
> #===
>
>
Technically, your use of globals() instead of locals(), like I did, is
better, in that it allows you to have it inside a function body, and still
be available at the module level, as per your stated goal.

However, I find the use of lambda to be too restrictive, in principle, as it
obviously works only for expressions, and not complex functions.  If this
example is to be used as a prototype to show students how to do this kind of
name assignment, then the way I have done it with an inner named function
(which I first learned about *years* ago, from a post from you on edu-sig!
I believe it was
http://mail.python.org/pipermail/edu-sig/2005-March/004590.html) is a better
way to go.


> Kirby
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20100527/a1d55999/attachment.html>


More information about the Edu-sig mailing list