Magic function

Mike Meyer mwm at mired.org
Fri Jan 11 17:51:17 CET 2008


On Fri, 11 Jan 2008 08:29:18 -0800 (PST) dg.google.groups at thesamovar.net wrote:

> Hi all,
> 
> I'm part of a small team writing a Python package for a scientific
> computing project. The idea is to make it easy to use for relatively
> inexperienced programmers. As part of that aim, we're using what we're
> calling 'magic functions', and I'm a little bit concerned that they
> are dangerous code. I'm looking for advice on what the risks are (e.g.
> possibility of introducing subtle bugs, code won't be compatible with
> future versions of Python, etc.).
> 
> Quick background: Part of the way our package works is that you create
> a lot of objects, and then you create a new object which collects
> together these objects and operates on them. We originally were
> writing things like:
> 
> obj1 = Obj(params1)
> obj2 = Obj(params2)
> ...
> bigobj = Bigobj(objects=[obj1,obj2])
> bigobj.run()
> 
> This is fine, but we decided that for clarity of these programs, and
> to make it easier for inexperienced programmers, we would like to be
> able to write something like:
> 
> obj1 = Obj(params1)
> obj2 = Obj(params2)
> ...
> run()
> 
> The idea is that the run() function inspects the stack, and looks for
> object which are instances of class Obj, creates a Bigobj with those
> objects and calls its run() method.
> 
> So, any comments on that approach?

The basic idea is ok, but looking at the stack makes me a bit
nervous. That makes the code complicated, and probably fragile in the
face of changing python versions.

The unittest module does much the same thing - you run unittest.main,
and it runs all the tests in any TestCase subclass in your module
(assuming you didn't do something to limit it). However, it does it by
examining the module, not the stack. The real difference is that your
"magic" classes have to be global to your module. On the other hand,
it provides some nice tools to let you partition things, so you can
easily run subsets of the classes from the command line.

It's probably worth a look.

     <mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.



More information about the Python-list mailing list