Accessing list items with getattr/setattr in Python

insomniaccanuck picture insomniaccanuck · Aug 1, 2011 · Viewed 15.4k times · Source

Trying to access/assign items in a list with getattr and setattr funcions in Python. Unfortunately there seems to be no way of passing the place in the list index along with the list name.
Here's some of my tries with some example code:

class Lists (object):
  def __init__(self):
    self.thelist = [0,0,0]

Ls = Lists()

# trying this only gives 't' as the second argument.  Python error results.
# Interesting that you can slice a string to in the getattr/setattr functions
# Here one could access 'thelist' with with [0:7]
print getattr(Ls, 'thelist'[0])


# tried these two as well to no avail.  
# No error message ensues but the list isn't altered. 
# Instead a new variable is created Ls.'' - printed them out to show they now exist.
setattr(Lists, 'thelist[0]', 3)
setattr(Lists, 'thelist\[0\]', 3)
print Ls.thelist
print getattr(Ls, 'thelist[0]')
print getattr(Ls, 'thelist\[0\]')

Also note in the second argument of the attr functions you can't concatenate a string and an integer in this function.

Cheers

Answer

warvariuc picture warvariuc · Aug 1, 2011
getattr(Ls, 'thelist')[0] = 2
getattr(Ls, 'thelist').append(3)
print getattr(Ls, 'thelist')[0]

If you want to be able to do something like getattr(Ls, 'thelist[0]'), you have to override __getattr__ or use built-in eval function.