Dynamically defined functions via exec in imported module

Nadeem nadeemabdulhamid at gmail.com
Fri Aug 15 22:48:23 EDT 2008


I understand the 99% rule... the example I gave was to simplify the
issue. The full thing I'm working on is a library for an introductory
CS class I'm teaching. I'm trying, essentially, to build a library of
macros for students to use allowing them to define records (like
structs in C) with selector functions. In particular, I'm trying to
replicate some of the Scheme stuff from the HtDP project in Python
(http://www.htdp.org/2003-09-26/Book/curriculum-Z-
H-9.html#node_sec_6.3). I want to provide a function, called
defineStruct that is called like this:

defineStruct('pos', 'x', 'y')

The effect of this function will be to dynamically define several new
functions for working with structures:

makePos(x, y)
posX(p)
posY(p)
isPos(p)

I understand that all this can be done with classes and OO
programming, but the whole point of the HtDP curriculum is to
introduce students to programming in a pedagogically-effective way
using a functional approach instead of OO-first. They do it in Scheme,
which is primarily a f.p. language, and I'm trying to replicate a
similar approach in Python. The defineStruct thing is basically meant
to be a macro that introduces a set of functions for whatever
structure definition is needed.

So, for these reasons, I don't believe the closure example above is
helpful. I don't want to have to tell students anything about
closures, and certainly have them worrying about functions returning
functions, and function pointers, etc. I'm trying to bundle all that
up behind the scenes.

So, thinking about my problem again, an alternate question may be: Is
it possible, in a function called in a module, to access and update
the global definitions (dictionary or whatever) in the caller module.

--- nadeem



More information about the Python-list mailing list