Home » Questions » Computers [ Ask a new question ]

Using 'in' to match an attribute of Python objects in an array

Using 'in' to match an attribute of Python objects in an array

"I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,

foo in iter_attr(array of python objects, attribute name)

I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers"

Asked by: Guest | Views: 423
Total answers/comments: 4
Guest [Entry]

"Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before in could start its search.

The temporary list can be avoiding by using a generator expression:

foo = 12
foo in (obj.id for obj in bar)

Now, as long as obj.id == 12 near the start of bar, the search will be fast, even if bar is infinitely long.

As @Matt suggested, it's a good idea to use hasattr if any of the objects in bar can be missing an id attribute:

foo = 12
foo in (obj.id for obj in bar if hasattr(obj, 'id'))"
Guest [Entry]

"Are you looking to get a list of objects that have a certain attribute? If so, a list comprehension is the right way to do this.

result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')]"
Guest [Entry]

"you could always write one yourself:

def iterattr(iterator, attributename):
for obj in iterator:
yield getattr(obj, attributename)

will work with anything that iterates, be it a tuple, list, or whatever.

I love python, it makes stuff like this very simple and no more of a hassle than neccessary, and in use stuff like this is hugely elegant."
Guest [Entry]

"No, you were not dreaming. Python has a pretty excellent list comprehension system that lets you manipulate lists pretty elegantly, and depending on exactly what you want to accomplish, this can be done a couple of ways. In essence, what you're doing is saying ""For item in list if criteria.matches"", and from that you can just iterate through the results or dump the results into a new list.

I'm going to crib an example from Dive Into Python here, because it's pretty elegant and they're smarter than I am. Here they're getting a list of files in a directory, then filtering the list for all files that match a regular expression criteria.

files = os.listdir(path)
test = re.compile(""test\.py$"", re.IGNORECASE)
files = [f for f in files if test.search(f)]

You could do this without regular expressions, for your example, for anything where your expression at the end returns true for a match. There are other options like using the filter() function, but if I were going to choose, I'd go with this.

Eric Sipple"