Best way to enumerate something in python
Peter Hansen
peter at engcorp.com
Thu May 27 10:40:05 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
Any time you see a pattern of repetition like this, you can
make improvements, at least with Python if not some other
languages. If nothing else, this will generally vastly improve
maintainability, and often readability as well.
>>> cols = 'NAME ADDRESS CITY ZIPCODE STATE COUNTRY SS CAT DATE SALARY'
>>> mycol = {}
>>> for i,col in enumerate(cols.split()):
... globals()[col + '_COL'] = i
... mycol[i] = ' %s ' % col
...
>>> dir()
['ADDRESS_COL', 'CAT_COL', 'CITY_COL', 'COUNTRY_COL', 'DATE_COL',
'NAME_COL', 'SALARY_COL', 'SS_COL', 'STATE_COL', 'ZIPCODE_COL',
'__builtins__', '__doc__', '__name__', 'col', 'cols', 'enum', 'i', 'mycol']
>>> mycol[CITY_COL]
' CITY '
-Peter
More information about the Python-list
mailing list