5

This is code I have, but it looks like non-python.

def __contains__(self, childName): """Determines if item is a child of this item""" for c in self.children: if c.name == childName: return True return False 

What is the most "python" way of doing this? Use a lambda filter function? For some reason very few examples online actually work with a list of objects where you compare properties, they always show how to do this using a list of actual strings, but that's not very realistic.

1
  • 1
    You code is quite self explanatory. Be happy with it and move to next problem :) Commented Aug 19, 2011 at 0:01

3 Answers 3

7

I would use:

return any(childName == c.name for c in self.children) 

This is short, and has the same advantage as your code, that it will stop when it finds the first match.

If you'll be doing this often, and speed is a concern, you can create a new attribute which is the set of child names, and then just use return childName in self.childNames, but then you have to update the methods that change children to keep childNames current.

Sign up to request clarification or add additional context in comments.

6 Comments

any() is what im looking for. but i still think python is retarded for making this a global function.
1) I wish you could use a different word than "retarded" to express your displeasure. 2) What should it be other than a global function?
a function of the list. mylist.any(expr)
There's no list here: the expression in the any() is a generator expression. The any() function can take any iterator as its argument, so there's no common base class to house a method.
ok then this goes deeper into my disagreements with some python choices. iterator should be a class that has the any method.
|
5

I would do this:

return childName in [c.name for c in self.children] 

2 Comments

This has the disadvantage of iterating all of self.children, and creating an intermediate list.
That is exactly what I was wondering about. Your solution obviates the problem: any(childName == c.name for c in self.children)
1

one way to do it with lambda:

from itertools import imap return any(imap(lambda c: c.name == childName, self.children)) 

but the original solution seems clearer to me.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.