Magic function

Ruediger larudwer at freenet.de
Fri Jan 11 21:20:41 CET 2008


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.


Well i would do it this way:
no fancy stuff, all standard and fast.

from weakref import ref

class bigobject(set):
    def __iter__(self):
        for obj in set.__iter__(self):
            yield obj()
    def run(self):
        for obj in self:
            print obj.value

class foo(object):
    """ weakref doesn't prevent garbage collection if last instance
          is destroyed """
    __instances__ = bigobject()
    def __init__(self, value):
        foo.__instances__.add(ref(self,foo.__instances__.remove))
        self.value = value

if __name__ == "__main__":
    obj1 = foo("obj1")
    obj2 = foo("obj2")
    obj3 = foo("obj3")
    obj4 = foo("obj4")
    foo.__instances__.run()
    print "test garbage collection."
    del obj1, obj2, obj3, obj4
    foo.__instances__.run()









More information about the Python-list mailing list