
On Sat, 24 Oct 2009 10:26:27 am Ben Finney wrote:
Steven D'Aprano <steve@pearwood.info> writes:
On Sat, 24 Oct 2009 06:04:12 am Terry Reedy wrote:
fwiw, I think the use case for this is sufficiently rare that it does not need a separate method just for this purpose.
And yet it keeps coming up, again and again... obviously people using sets in code think it has a use-case.
The desire for this may be obvious, but what seems to be lacking is One Obvious Way to Do It.
I agree that ‘for x in foo_set: break’ is not an Obvious Way.
The lack of get() in sets and frozensets is sounding more and more to me like the victory of purity over practicality.
What would be the input to ‘set.get’?
It wouldn't take any input.
If it's the value, that makes it rather non-obvious;
It makes it pointless if it takes the value. If you already have the value, why would you need to retrieve it from the set?
if I already know about ‘dict.get’ which takes the key, I'm not going to be thinking about the ‘get’ method if I don't have a key to feed it. Once I learn it, I'm going to forget it easily, because it's inconsistent with ‘dict.get’. So I don't think that meets the “obvious way” criterion.
"get" is such a generic term that I don't believe that is a problem. There are already quite a number of get() methods in the 2.6 std lib: $ grep "def get[(]" *.py _abcoll.py: def get(self, key, default=None): ConfigParser.py: def get(self, section, option): ConfigParser.py: def get(self, section, option, raw=False, vars=None): doctest.py: def get(self): mailbox.py: def get(self, key, default=None): os.py: def get(self, key, failobj=None): pickle.py: def get(self, i, pack=struct.pack): Queue.py: def get(self, block=True, timeout=None): shelve.py: def get(self, key, default=None): sre_parse.py: def get(self): threading.py: def get(self): UserDict.py: def get(self, key, failobj=None): UserDict.py: def get(self, key, default=None): weakref.py: def get(self, key, default=None): weakref.py: def get(self, key, default=None): webbrowser.py:def get(using=None): I think you over-estimate the degree of confusion people suffer from similar sounding methods. I don't think people are confused that dict[key] and list[index] have different semantics, and I don't see why dict.get(key[, default]) and set.get() would be any different. But if you don't like get(), spell it differently. There's plenty of opportunity for bike-shedding: getitem() getelement() get_arbitrary_element() peek() etc.
By analogy with ‘list.pop’, the method that takes the “top” item off the “stack”, I would expect to see ‘list.peek’ and ‘set.peek’, to see the item without altering the container.
You don't need list.peek() because there already is an obvious way to retrieve an item from a list without removing it: list[index]. -- Steven D'Aprano