referring from within containers objects

Dimitris Garanatsios dg96057 at teledomenet.gr
Mon Mar 10 08:10:56 EST 2003


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

I think that the need of refering to the elements of a container at the 
time it is created is quite rare and usually means bad design of the 
data structures it represents. Your proposal would propably require a 
two step process for the creation of a container (especially for 
dictionaries) at python's C implementation, unless more strict rules 
would apply, such as to only refer to elements already specified.

In case my english confuse anyone (sorry about that...), this means that 
code like

lst = [ _[1] + ' ' + _[2], 'Nit', 'Wit' ]

whould raise some kind of an error.

In my opinion this whould result in an uglier syntax (for the C level 
ofcourse) that slows down an object's creation without a good reason...

For your example i would use a class definition instead of a dictionary like

class Baptize:
     def __init__(self, fname, mname, lname):
         self.fname = fname
         self.mname = mname
         self.lname = lname
         self.fullname = fname +' '+ mname +' '+ lname

and instantiate it like

baby = Baptize('Pretty', 'Python', 'Syntax')

:-)

Regards,
Dimitris





More information about the Python-list mailing list