0

I need to add more values to a list of WSHandler connections (Tornado, Python). I'm adding the connection to a list like so self.connections.append(self), but I need to add more information, like self.connections.append({'id': self, 'keyword' : ''}) (and later find the current self id and replace the keyword.)

When I try to add to the list based on self object (like self.connections[self].filter = 'keyword'), I get TypeError: list indices must be integers, not WSHandler.

So how can I do this?

Edit: Managed to find the right object like so:

def on_message(self, message):
    print message
    for x in self.connections:
        if x['id'] == self:
            print 'found something'
            x['keyword'] = message
            print x['keyword']
            print x

Now, how do I remove the whole dict from connections ? self.connections.remove(self) no longer works, of course.

2 Answers 2

3

For this use case, you do not need a list of connections. It may be easier to store this in the object itself. Simply use self.filter = 'keyword'.

Otherwise:

for dict in self.connections:
    if dict['id'] == self:
        dict['keyword'] = 'updated'

Or, if you favour brevity over clarity:

for dict in [dict for dict in self.connections if dict['id'] == self]:
    dict['keyword'] == 'updated'

To remove, use:

for dict in self.connections:
    if dict['id'] == self:
        self.connections.remove(dict)
4
  • Thanks. But it has to match the correct ID in the list of connections. How do I make sure it's the right one?
    – knutole
    Oct 2, 2012 at 11:55
  • Ah yes, I think you're right - easier just storing in the object itself.
    – knutole
    Oct 2, 2012 at 12:04
  • Basically, if the object you are looking for is self then there is no need to retrieve it from the connection based on its id. In your code fragment you do not show where you store the matching id. Where is that?
    – Hans Then
    Oct 2, 2012 at 12:09
  • Actually, there is no 'id', it's just my shortname for the self object. See edit.
    – knutole
    Oct 2, 2012 at 12:21
1

Since self.connections is a list, you can only index it using an integer (as the error says). self here is a WSHandler object, not an integer.

I'm not an expert on Tornado, so you should try what Hans says.

If you still need to do it the way you've mentioned, try: self.connections[self.connections.index(self)] to locate the self object in the list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.