pass objects to exec

Alex Martelli aleax at aleax.it
Mon Mar 24 05:24:41 EST 2003


zunbeltz wrote:
    ...
> Tanks for answer.  Group class need a second argument, it is a string
> similar to that in the dictionary key. Can I use something like that
>        d = {}
>        for i in range(len(MemberList)):
>            d['GroupA-%c' % (i + ord('A'))] =
> Group(MemberList[i],'GroupA-%c' %(i+ òrd('A')))

Yes, this is quite correct code (apart from one too-long line getting
broken).  But I would recommend never repeating code of any complexity,
such as the expression computing the string -- computer it ONCE then
use it, i.e.:

       d = {}
       for i in range(len(MemberList)):
           gname = 'GroupA-%c' % (i + ord('A'))
           d[gname] = Group(MemberList[i], gname)

Python 2.3 lets you code this a tad more elegantly, IMHO:

       d = {}
       for i, igroup in enumerate(MemberList):
           gname = 'GroupA-%c' % (i + ord('A'))
           d[gname] = Group(igroup, gname)

and an alternative that also works with earlier Python version is:

       import string
       d = {}
       for c, igroup in zip(string.uppercase, MemberList):
           gname = 'GroupA-%c' % c
           d[gname] = Group(igroup, gname)


Alex





More information about the Python-list mailing list