referring from within containers objects

Bengt Richter bokr at oz.net
Fri Mar 14 14:46:02 EST 2003


On 10 Mar 2003 02:11:48 -0800, sandskyfly at hotmail.com (Sandy Norton) wrote:

>Hi,
>
>This is just an idea that occurred to me while working with
>dictionaries in which the values of certain keys were composed of the
>values of other keys and I found that the syntax for solving that
>problem wasn't as pretty as I would have liked. 
>
>Here's an example:
>
>d = {
>  'fname' : 'Nit',
>  'lname' : 'Wit'
>}
>
>Now I have to do this:
>
>d['fullname'] = d['fname'] + ' ' + d['lname']
>
>if I want to reuse the keys/values within the dict. This forces me to
>break out of the dictionary definition, which I don't like doing for
>some reason.
>
>Now what if I could do something like this: 
>
>d2 = {
>    'fname' : 'Nit',
>    'lname' : 'Wit',
>    'fullname' : _['fname'] + ' ' + _['lname']
>}   
>
>where '_' refers to the containing dict.
>
>This can be extended to lists:
>
>lst = [ 'Nit', 'Wit', _[0] + ' ' + _[1] ]
>
>
>Sandy

You could subclass dict to retrieve compositions of key values
in specialized ways, e.g., (not tested beyond what you see below):

====< compose.py >=========================================
class Compose(object):
    def __init__(self, fmt, *keys):
        self.fmt = fmt
        self.keys = keys
    def __call__(self, dct):
        return self.fmt % tuple(map(dct.__getitem__, self.keys))

class Cdict(dict):
    def __getitem__(self, key):
        v = dict.__getitem__(self, key)
        if isinstance(v, Compose): return v(self)
        return v

cd = Cdict()
cd['fname']='Nit'
cd['lname']='Wit'
cd['fullname'] = Compose('%s-%s', 'fname', 'lname')
print cd['fname']
print cd['lname']
print cd['fullname']
cd['lname'] = 'Twit'
print cd['fullname']
d2 = Cdict({
    'fname' : 'Nit',
    'lname' : 'Wit',
    'fullname' : Compose('%s %s', 'fname', 'lname')
})
print d2['fullname']
===========================================================

The output is:

[11:52] C:\pywk\clp>compose.py
Nit
Wit
Nit-Wit
Nit-Twit
Nit Wit

Note that just changing the lname key value caused a change in
the sythesized 'fullname' value. d2 is initialized with a literal
more or less like your format. Of course you can use other ways
to make synthetic key values.

Regards,
Bengt Richter




More information about the Python-list mailing list