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

kirby urner kirby.urner at gmail.com
Wed May 26 21:58:20 CEST 2010

Creating Top-Level names root0, root1, root2... rootN

Setting the stage:

We've come across an ethnicity, in our voyages
of the starship whatever, that doesn't share our
fascination with squares and cubes.  For example,
when multiplying n * n, it never occurred to them
to picture n * n squares in a checkerboard pattern.
Rather, they have a more Chinese Checkers bias
towards triangles and hexagons, and their picture
of n * n is an equilateral triangle subdivided into
n ** 2 similar sub-triangles.

Likewise, their picture of n * n * n, or n**3 is a
tetrahedron, though here the subdividing process
results in a matrix known to Earthlings ("terra-ists")
as the FCC and/or CCP and/or... whatever Earthling

The Challenge:

The anthropologist-astronauts we've left behind
to work and study with these people (to be
collected on a next pass a year from now, unless
they plan on staying longer), are using Python, and
find that saying 'sqrt' just gets in the way (keeps
them habituated to patterns of thought they're trying
to snap out of).

What they'd like to do is this:  for 2nd, 3rd, 4th,
5th etc. root of a number, have the functions
root2, root3, root4... up to root10 routinely available,
perhaps in a module called roots or radicals.

>>> import radicals as r
>>> r.root3 ( 2.0 / 3.0 )

So how might we generate root0... root10 in a
factory function, such that these function names
become top level within their generating and/or
defining module?

True, we could individually define these functions
per the example below, but what is a clever way
of generating rootN in principle, such as root2012,
taking 2012 as an argument.


For root2, you might take an obvious shortcut:

from math import sqrt as root2

For root3, consider the following:

def root3 (x):  return pow( x, 1.0/3.0 )

In general:

def rootN (x):  return pow( x, 1.0/N)

Rationale for this exercise:

Students often want a way to factory-produce
new names at the top level, from within a contained
scope (such as from within a function).

These top level names may be of data, functions or
whatever arbitrary objects.  The production process
often involves synthesizing new names on the fly,
as strings.  Strings are "right side" objects, usually
assigned names, but not themselves names of

By what magic might we turn a string object into
a top-level name:  that is the question this lesson
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20100526/86dd9ed3/attachment.html>

More information about the Edu-sig mailing list