Dynamically defined functions via exec in imported module

Nadeem nadeemabdulhamid at gmail.com
Sat Aug 16 05:44:12 CEST 2008

That's a really neat way of doing it, thanks a lot! I hadn't realized
how accessible all those globals() dictionaries were. Guess my example
still falls in the 99%... :)
--- nadeem

> def defineStruct(name, *parameters):
>   class _struct:
>     def __init__(self, *init_parameters):
>       for pname, pvalue in zip(parameters, init_parameters):
>         setattr(self, pname, pvalue)
>   globals()["make" + name] = _struct
>   for parameter in parameters:
>     def getter(o, parameter=parameter):
>       return getattr(o, parameter)
>     globals()[name + parameter] = getter
>   globals()["is" + name] = lambda o: isinstance(o, _struct)
> You might do other things, of course, like stepping up the frames from
> sys._getframe() to inject the functions into the callers global scope.
> There are some obvious optimizations you could make, too, as well as
> other "methods" you might want to add.
> > 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
> > --
> >http://mail.python.org/mailman/listinfo/python-list
> --
> Read my blog! I depend on your acceptance of my opinion! I am interesting!http://techblog.ironfroggy.com/
> Follow me if you're into that sort of thing:http://www.twitter.com/ironfroggy

More information about the Python-list mailing list