Array design question

Carl Banks imbosol at aerojockey.com
Fri May 30 13:54:47 EDT 2003


Dave Benjamin wrote:
> Python has no equivalent
> (to my knowledge) of this:
> 
> $a = array();
> ...
> $a[0][2] = 'hello';
> ...
> $a[1][3] = 'world';
> 
> Python would make you do this:
> 
> a = {}
> ...
> a.setdefault(0, {})
> a[0][2] = 'hello'
> ...
> a.setdefault(1, {})
> a[1][3] = 'world'
> 
> In other words, PHP will actually create nested arrays (I'm using the term
> "array" in the PHP sense) on the fly if you use multiple indexes. You could
> say:
> 
> $a[0][0][0][0] = 'ramen';
> 
> And you'd actually get a quadruply-nested array. Even if $a doesn't exist.


    class autonestdict(dict):
        def __getitem__(self,attr):
            try:
                return super(autonestdict,self).__getitem__(attr)
            except KeyError:
                return _autonestclosure(self,attr)

    class _autonestclosure(object):
        def __init__(self,nest,attr):
            self.nest = nest
            self.attr = attr
        def __getitem__(self,attr):
            return _autonestclosure(self,attr)
        def __setitem__(self,attr,value):
            obj = autonestdict()
            obj[attr] = value
            self.nest[self.attr] = obj


Except it's error prone, because it never raises a KeyError.
(Although it's still not any worse than the PHP/Perl behavior.)


-- 
CARL BANKS




More information about the Python-list mailing list