python list/dict property best practice

Posted by jterrace on Stack Overflow See other posts from Stack Overflow or by jterrace
Published on 2011-03-16T22:58:24Z Indexed on 2011/03/17 0:09 UTC
Read the original article Hit count: 225

Filed under:

I have a class object that stores some properties that are lists of other objects. Each of the items in the list has an identifier that can be accessed with the id property. I'd like to be able to read and write from these lists but also be able to access a dictionary keyed by their identifier. Let me illustrate with an example:

class Child(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name

class Teacher(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name

class Classroom(object):
    def __init__(self, children, teachers):
        self.children = children
        self.teachers = teachers

classroom = Classroom([Child('389','pete')],
                      [Teacher('829','bob')])

This is a silly example, but it illustrates what I'm trying to do. I'd like to be able to interact with the classroom object like this:

#access like a list
print classroom.children[0]
#append like it's a list
classroom.children.append(Child('2344','joe'))
#delete from like it's a list
classroom.children.pop(0)

But I'd also like to be able to access it like it's a dictionary, and the dictionary should be automatically updated when I modify the list:

#access like a dict
print classroom.childrenById['389']

I realize I could just make it a dict, but I want to avoid code like this:

classroom.childrendict[child.id] = child

I also might have several of these properties, so I don't want to add functions like addChild, which feels very un-pythonic anyway. Is there a way to somehow subclass dict and/or list and provide all of these functions easily with my class's properties? I'd also like to avoid as much code as possible.

© Stack Overflow or respective owner

Related posts about python