Ian Bicking: the old part of his blog


A Ruby program has great capacity for "reflection", the ability to observe itself. Want a list of all living objects belonging to a particular class? No problem! Should you enjoy life in the fast lane, a ruby program can effectively rewrite itself at run-time.
Python's reflection is quite good. The list of all living objects, however, does not exist.
You can, however, make a class that can provide a list of all living instances. That's what I did when I hacked Routes support into web.py:
class controller(object):
    registry = {}
    class __metaclass__(type): 
        def __init__(cls, name, bases, dict): 
            if not ('register' in dict):
    def register(cls, thecls):
        cls.registry[thecls.__name__] = thecls
    def subclasses(cls):
        return cls.registry.keys()
Yeah, it's ugly. But it works.
Comment on Re: Ruby and Python Compared
by Jon Rosebaugh


That's to find all subclasses, not all instances. I remembered about the gc module, though, and this kind of works:

def all_instances(a_class):
    return [obj for obj in gc.get_objects() if isinstance(obj, a_class)]

People use things like this to do reloading in Python. Once someone says "yes, I do reloading, and it works like a dream and never fails" then I'll be all over that. But it seems like there's some other tricks to do it right.

# Ian Bicking

Whups, yeah.

A similar principle would work, though.

# Jon Rosebaugh

"Yeah, it's ugly. But it works."

That's the point. Ruby does it with elegance.

# Dan Chokola