Best way to enumerate something in python

Michael Geary Mike at DeleteThis.Geary.com
Thu May 27 13:01:54 EDT 2004


David Stockwell wrote:
> FWIW this is what I'm going to do for enumerated types in python.
> Its not perfect but it will make it fairly easy to get at column names
> so I can build SQL statements on the fly and still have fairly easy to
> maintain code
>
> #setup stuff
> NAME_COL,     ADDRESS_COL,    CITY_COL,  ZIPCODE_COL, \
> STATE_COL,    COUNTRY_COL,    SS_COL,    CAT_COL, \
> DATE_COL,     SALARY_COL                              = range(10)
>
> mycol = {
>       NAME_COL: " NAME ",   ADDRESS_COL: " ADDRESS ",
>       CITY_COL: " CITY ",   ZIPCODE_COL: " ZIPCODE ",
>       STATE_COL:" STATE ", COUNTRY_COL:  " COUNTRY ",
>       SS_COL:   " SS ",       CAT_COL:   " CAT ",
>       DATE_COL: " DATE ",   SALARY_COL:  " SALARY " }
> # Use these for indexing by column name
>
> # demonstration on how to 'get'
>
> print mycol[CITY_COL]

I don't know much about SQL, so this may be a dumb question, but... Is it a
requirement that you have indices for the columns as well as names? IOW,
does it matter that NAME_COL is 0, ADDRESS_COL is 1, etc.? Or is the end
result you're after to have NAME_COL be a way to get to the string " NAME "?

If you don't need the numeric indices, there are a couple of other
approaches you could take, both inspired by Peter Hansen's nifty bit of
code:

First, since you're putting CITY_COL and so forth in the global namespace
anyway, you could simply define them as the strings:

def makeColumnNames( names ):
    class container: pass
    cols = container()
    for c in names.split():
        cols.__dict__[c] = ' %s ' % c
    return cols

cols = makeColumnNames(
    'NAME ADDRESS CITY ZIPCODE STATE COUNTRY SS CAT DATE SALARY' )

print "'%s'" % cols.CITY

Or, you could avoid cluttering up the global namespace with those names,
avoid the need for the _COL suffix, and use the cleaner cols.CITY notation
instead of cols[CITY_COL]:

def makeColumnNames( names ):
    class container: pass
    cols = container()
    for c in names.split():
        cols.__dict__[c] = ' %s ' % c
    return cols

cols = makeColumnNames(
    'NAME ADDRESS CITY ZIPCODE STATE COUNTRY SS CAT DATE SALARY' )

print "'%s'" % cols.CITY

If you do need the numeric indices as well, it would be easy to come up with
a variation of one of the above approaches that gives you both the indices
and the names in a convenient way.

-Mike





More information about the Python-list mailing list