Dictionary type access to list of instances

Grant Beasley gbeasley at tsa.ac.za
Tue Feb 26 02:44:33 EST 2002


Thanks for the response

Firstly, I really like your NotEqual class, it solves a bunch of other
problems I'm experiencing, because as you point out, None can sometimes be a
valid value.

The only part I don't like about your solution is the fact that the
properties array will be generated for all instances, whereas, using a for
loop that returns the instance when it finds it, not all instances need to
be inspected for the property. So this might result in better efficiency (In
the best case where the instance required is the first in the list).

Obviously catching the attribute exception is a better solution though, and
I'll probably integrate that into my solution. Currently I'm using my filter
solution just because I tend to prefer things I can do on one line instead
of having to write a complete new subroutine (which is why I enjoy Python so
much), but I'll probably adapt that soon.

What I'm ultimately aiming for is a database-like view of a list of
instances, so that I can use SQL commands to get instances. So in the
analogy, a list of instances would be a table, with each instance a record,
and each property a field.

eg.
class User:
    def __init__(self, username, accesslevel):
        self.username = username
        self.accesslevel = accesslevel

list = [User('Bob', 1), User('Jim', 2), User('Pete', 2)]

Then using my imaginary function ListSQL:

ListSQL("select * from list where accesslevel = 2")
would return a list consisting of the Jim and Pete instances.

or ListSQL("select username, accesslevel from list where accesslevel = 2")
would return [('Jim', 2), ('Pete',2)] - i.e. a List of tuples.

Is this an interesting / useful idea? Has it been done before? Any comments?

Thanks
Grant

"Brian Kelley" <bkelley at wi.mit.edu> wrote in message
news:3C7A5AD4.9090404 at wi.mit.edu...
> Grant Beasley wrote:
>
> > Hi
> >
> > If I have a list of instances, each with a property which I want to use
as a
> > key to access the list in dictionary-like manner, what would be the best
 way
> > of doing this?
> >
> > eg.
> > func get(list, property, value):
> >     for x in list:
> >         if getattr(x, property) == value:
> >             return x
> >
>
> In this usage, getattr will raise an Attribute error if property doesn't
> exist which might not be what you want.
>
> Here is an attempt using list comprehensions and the built-in list.index
> function.  I have created a NotEqual class so that getattr can return a
> default value is never equal to any other instance.  This is because
> None might be a valid value for a property.
>
> class NotEqual:
>      """instances of this class are never equal to anything"""
>      def __eq__(self, other):
>          return 0
>
> def get(inputList, property, value, default=NotEqual()):
>      try:
>          properties = [getattr(x, property, default) for x in inputList]
>          return inputList[properties.index(value)]
>      except ValueError:
>          raise ValueError, "attribute %s with value %s not found"%(
>              `property`, `value`)
>
> if __name__ == "__main__":
>      class Foo:
>          def __init__(self):
>              self.dog = 1
>
>      foo = Foo()
>      print get([foo], 'dog', 1)
>      try:
>          get([foo], 'dog', 2)
>      except ValueError, msg:
>          print 'error caught:', msg
>
>      try:
>          get([foo], 'cat', 'raisin')
>      except ValueError, msg:
>          print 'error caught:', msg
>





More information about the Python-list mailing list