On Wed, Oct 31, 2018 at 08:41:28PM +1100, Chris Angelico wrote:
On Wed, Oct 31, 2018 at 8:24 PM Nicolas Rolin
wrote: As a user I always found a bit disurbing that dict pop method have a default while list and set doesn't. While it is way more computationally easy to check wether a list or a set is empty that to check if a key is in a dict, it still create a signature difference for no real reason (having a default to a built-in in python is pretty standard). It would be nice if every built-in/method of built-in type that returns a value and raise in some case have access to a default instead of raise, and not having to check the doc to see if it supports a default.
https://www.python.org/dev/peps/pep-0463/ wants to say hi.
PEP 463 is too busy crying bitter tears in the corner after being rejected to say "Hi". I don't think this is the same thing: PEP 464 is about being able to catch arbitrary exceptions in arbitrary expressions in an ad-hoc manner. Nicholas' suggestion is about making a consistent strategy of avoiding the need to catch exceptions. I don't think I would agree with a broad rule "anything that raises can return a default value" -- I don't think it makes sense to have, let's say, len(obj, default=2). But on a case-by-case basis, it works for me. If this were Ruby, and we could monkey-patch the built-in types, my reasoning would go something like this: - if I have to write "L.pop() if L else default", I should write it in place; - the third time I write it in any one module, I ought to factor it out into a helper function; - the third time I write the helper function, I ought to just monkey-patch the built-in and be done with it. I haven't been counting, but I'm pretty sure I've written "get(L, index, default)" and "pop(L, index, default)" helpers at least three times now. Possibly even three times each :-) In Python, of course, we can't add methods to built-ins. But I think this functionality makes good sense, especially once we remember that pop takes an optional index. Spot the bug in this: L.pop(idx) if len(L) > idx else default -- Steve