Re: Best way to enumerate something in python

Discussion in 'Python' started by David Stockwell, May 26, 2004.

  1. Thanks for the help.

    I found out range creates lists not tuples, so apparently they can get
    changed (for an enum type approach).

    I'm going to use them in SQL statements that get generated on the fly. I
    need to be able to refer to a particular column in a meaningful way which
    is why if i had an enumerated type it might be easy to do so.

    i did some reading and if i interpreted this correctly, dictionaries are
    hashed, correct? If so i might be able to get away with referencing the
    dictionary and passing the hashkey in this case a number to retrieve the
    column name. However, I'd like to do this mnemonically so I can refer to
    the column name with a short cut name that makes sense instead of saying
    something like

    insrtCommand = ' select ' + columns[1] + ',' + columns[2] + ' from '
    blah.......

    from a maintenance standpoint, the programmer can't tell what column 1 is
    supposed to refer to. however if i had something like

    columns[HOUSING_ID] instead of the '1' then the programmer would later at
    a glance be able to follow the code.




    David
    -------
    tracfone: http://cellphone.duneram.com/index.html
    Cam: http://www.duneram.com/cam/index.html
    Tax: http://www.duneram.com/index.html




    >From: "Larry Bates" <>
    >To:
    >Subject: Re: Best way to enumerate something in python
    >Date: Wed, 26 May 2004 08:54:10 -0500
    >
    >David,
    >
    >You may have to give us more detail about what
    >you want to do, but here goes:
    >
    >listofcolumns=('field1','field2','field3')
    >for column in listofcolumns:
    > <do something>
    >
    >Most of the time I find that putting the names
    >in a dictionary with the column name as key and
    >offset as the value seems to work better.
    >
    >dictofcolumns={'field1':1, 'field2': 2, 'field3':3}
    >
    >value_for_field3=row[dictofcolumns['field3']]
    >
    >For your second question I think you should
    >take a look at os.path.getatime, .gmtime, getsize
    >they are easier to use.
    >
    >Larry Bates
    >Syscon, Inc.
    >
    >
    >"David Stockwell" <> wrote in message
    >news:...
    > > Hi Everyone,
    > >
    > > I'm wondering about the best way to enumerate something.
    > >
    > > I have a list of columnames for a db and I decided to put them in a

    >giant
    > > tuple list for two reasons:
    > > 1) its unchangeable
    > > 2) I was hoping that creating an enumeration of those names would be

    >easy
    > >
    > > In the os.stat there is aparrently a list of things you can refer to eg:
    > > ST_SIZE, ST_ATIME, etc.
    > >
    > > How are these defined? They appear to be related to 0,1,2,3,.... some
    > > sort of enumeration.
    > >
    > > I would like to create an enumeration with 'friendly names' that map to

    >the
    > > particular offset in my column name tuple.
    > >
    > > Thanks,
    > >
    > >
    > >
    > > David
    > > -------
    > > tracfone: http://cellphone.duneram.com/index.html
    > > Cam: http://www.duneram.com/cam/index.html
    > > Tax: http://www.duneram.com/index.html
    > >
    > > _________________________________________________________________
    > > FREE pop-up blocking with the new MSN Toolbar – get it now!
    > > http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/
    > >
    > >

    >
    >
    >--
    >http://mail.python.org/mailman/listinfo/python-list


    _________________________________________________________________
    FREE pop-up blocking with the new MSN Toolbar – get it now!
    http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/
     
    David Stockwell, May 26, 2004
    #1
    1. Advertising

  2. David Stockwell

    tutu Guest

    >
    > insrtCommand = ' select ' + columns[1] + ',' + columns[2] + ' from '
    > blah.......
    >
    > from a maintenance standpoint, the programmer can't tell what column 1 is
    > supposed to refer to. however if i had something like
    >
    > columns[HOUSING_ID] instead of the '1' then the programmer would later at
    > a glance be able to follow the code.
    >

    I've been using something like the following (maybe it helps):
    import types

    class Field(object):
    "a field has a name , a value and an index in a row from a rowset"
    def __init__(self, name, value, idx):
    self.name =name
    self.value=value
    self.index=idx
    def __repr__(self): return self.name

    class Fields(object):
    def __init__(self, fields_dict):
    self._fields = fields_dict
    self.fieldsCount = len(self._fields.keys())
    self.row = None

    def _setFields(self):
    self._fldName = {}
    self._fldIdx = {}
    for nm, idx in self._fields.items():
    self._fldName[nm] = self._fldIdx[idx] = Field(nm,
    self._row is not None and self._row[idx] or None, idx)

    def __getitem__(self, fld):
    if type(fld) in [types.IntType, types.LongType]:
    if 0<=fld<=self.fieldsCount-1: return self._fldIdx[fld]
    raise IndexError, "Index out of bounds %d" % fld
    elif type(fld) in [types.StringType, types.UnicodeType]:
    if self._fldName.has_key(fld):
    return self._fldName[fld]
    raise ValueError, "No such field %s" % idx
    else:
    raise ValueError, "key may only be a text (field_name) or
    a number (field index in row)"

    def setRow(self, rowLst):
    self._row = rowLst
    self._setFields()

    row = property(fget= lambda self: self._row, fset = setRow)


    fields = Fields(dict(name=0, phone=1, address=2))
    sql = "select %s, %s, %s from addressbook" %
    (fields[0],fields[1],fields[2])
    print sql
    sql = "select %s from addressbook" % ",
    ".join((str(fields['name']),str(fields['phone']))) #needs str()
    because type(fields['name'])==Field not str
    print sql
    sql = "select %s, %s from addressbook" % (fields['name'].name,
    fields['phone'].name)
    print sql
    #r = cursor.execute(sql)
    #rows = r.fetchall()
    rows=(("jon","ext 391","jon address"),("bob","ext 294", "bob
    address"))
    for row in rows:
    fields.row=row
    print "by field name: name=%s\taddress=%s\tphone=%s" %
    (fields['name'].value, fields['address'].value, fields['phone'].value)
    print "by field index: name=%s\taddress=%s\tphone=%s" %
    (fields[0].value, fields[2].value, fields[1].value)
    print

    =>
    select name, phone, address from addressbook
    select name, phone from addressbook
    select name, phone from addressbook
    by field name: name=jon address=jon address phone=ext 391
    by field index: name=jon address=jon address phone=ext 391

    by field name: name=bob address=bob address phone=ext 294
    by field index: name=bob address=bob address phone=ext 294

    Good Look
     
    tutu, May 27, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David Stockwell

    Best way to enumerate something in python

    David Stockwell, May 26, 2004, in forum: Python
    Replies:
    2
    Views:
    328
    Hallvard B Furuseth
    May 26, 2004
  2. David Stockwell

    re best way to enumerate something in Python

    David Stockwell, May 26, 2004, in forum: Python
    Replies:
    2
    Views:
    333
    Michael Geary
    May 26, 2004
  3. David Stockwell

    Re: Best way to enumerate something in python

    David Stockwell, May 27, 2004, in forum: Python
    Replies:
    3
    Views:
    379
    Roy Smith
    May 27, 2004
  4. Дамјан ГеоргиевÑки

    Best way to enumerate classes in a module

    Дамјан ГеоргиевÑки, Jun 24, 2009, in forum: Python
    Replies:
    5
    Views:
    320
    Michele Simionato
    Jun 26, 2009
  5. Robert K.

    ruby way to enumerate users

    Robert K., Feb 1, 2004, in forum: Ruby
    Replies:
    9
    Views:
    224
    Rove Monteux
    Feb 2, 2004
Loading...

Share This Page