Dynamically defined functions via exec in imported module

Maric Michaud maric at aristote.info
Sat Aug 16 10:02:26 EDT 2008


Le Saturday 16 August 2008 06:50:02 Michele Simionato, vous avez écrit :
> On Aug 16, 4:48 am, Nadeem <nadeemabdulha... at gmail.com> wrote:
> > 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.
>
> The namedtuple recipe by Raymond Hetting does
> exactly that and, guess what, it uses exec!

It uses exec, but could not, and IMO, should not, all of the cooking could be 
done in the closure. I join version of it without exec. Of course the only 
drawback is that you need to do the job of argument checking in __new__ and 
can't rely on a dynamically compiled arglist. But it is a common idiom I 
think.

> Also the doctest module in the standard library
> uses exec at good effect. So, I would say it is
> not a 99% rule, let's say it is a 98% rule ;)

Yes, but in doctest, exec is used for what it is intended to be use, execute 
arbitrary code provided by the user, this is legal and perfect use of exec 
because here the user is a trusted one (the programer himself).

I'd say that everywhere exec/eval are used in a application/function/lib that 
doesn't mean to interpret arbitrary and user provided python code, it is a 
bad usage.




-- 
_____________

Maric Michaud
-------------- next part --------------
A non-text attachment was scrubbed...
Name: namedtuple.py
Type: application/x-python
Size: 5644 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20080816/b5ffad89/attachment-0001.bin>


More information about the Python-list mailing list