[IPython-dev] ipipe news

Walter Dörwald walter at livinglogic.de
Wed Mar 1 13:20:51 EST 2006


Ville Vainio wrote:

> Is there an easy way to create a Table "casually", without declaring
> any classes?
> 
> I'm thinking of api like
> 
> t = Table('name','address')
> 
> t.add(name='foo',address = 'bar')
> t.add(name='hello',address = 'world')
> 
> or perhaps even create it with list/tuple of dicts/arbitrary objects
> and try to do __getitem__, and failing that, getattr for 'name' and
> 'address' for every object in sequence.

If the object is a list or tuple, this already works:

     [("foo", "bar"), ("hello", "world")] | ibrowse

but if it isn't a sequence __xattr__() has to be implemented to get the 
list of attributes for the object, so you'd have to use a class that 
looks like this:

     class idict(dict):
         def __xattrs__(self, mode):
             return self.keys()
          def __getattr__(self, key):
             try:
                 return self[key]
             except KeyError:
                 raise AttributeError

With this you can do:

[idict(foo="foo", bar="bar"), idict(foo="hello", bar="world")] | ibrowse

But unfortunately with this the column order is undefined. But you can 
do something like this:

     class OnTheFlyTable(object):
         def __init__(self, *attrs):
             self.attrs = attrs

         def __call__(self, **kwargs):
             return idict(**kwargs)

     class idict(dict):
         def __init__(self, table, **kwargs):
             self.table = table
             dict.__init__(**kwargs)

         def __xattrs__(self, mode):
             return self.table.attrs

         def __getattr__(self, key):
             try:
                 return self[key]
             except KeyError:
                 raise AttributeError

Then you can do:

     t = OnTheFlyTable("foo", "bar")
     [t(foo="foo", bar="bar"), t(foo="hello", bar="world")] | ibrowse

If we add something like this to ipipe, we need better names for 
OnTheFlyTable and idict.

Bye,
    Walter Dörwald




More information about the IPython-dev mailing list