Python Forum
a suggestion for a feature change
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a suggestion for a feature change
#5
So it's kind of like the dict's .get() method, except it also .pop()'s the index?

What about something like this, wrapped up in a module so NoDefault is namespaced correctly?
>>> NoDefault = (None, )
>>> class DefaultList(list):
...   def _pop_default(self, index=0, default_value=NoDefault):
...     try:
...       value = self._pop_original(index)
...       return value
...     except IndexError as err:
...       if default_value is not NoDefault:
...         return default_value
...       raise err
...   def __init__(self, *args, **kwargs):
...     super().__init__(*args, **kwargs)
...     self._pop_original = self.pop
...     self.pop = self._pop_default
...
>>> items = DefaultList(["spam", "eggs", "foo", "bar"])
>>> items
['spam', 'eggs', 'foo', 'bar']
>>> items[3]
'bar'
>>> items.pop()
'spam'
>>> items
['eggs', 'foo', 'bar']
>>> items.pop(1)
'foo'
>>> items
['eggs', 'bar']
>>> items.pop(5, "default")
'default'
>>> items.pop(5, None)
>>> items.pop(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in _default_pop
  File "<stdin>", line 4, in _default_pop
IndexError: pop index out of range
>>> items
['eggs', 'bar']
Reply


Messages In This Thread
a suggestion for a feature change - by Skaperen - Jul-30-2017, 08:26 AM
RE: a suggestion for a feature change - by Larz60+ - Jul-30-2017, 03:19 PM
RE: a suggestion for a feature change - by DeaD_EyE - Jul-30-2017, 04:19 PM
RE: a suggestion for a feature change - by Skaperen - Jul-31-2017, 02:56 AM
RE: a suggestion for a feature change - by nilamo - Aug-02-2017, 09:06 PM
RE: a suggestion for a feature change - by Skaperen - Aug-03-2017, 07:09 AM
RE: a suggestion for a feature change - by DeaD_EyE - Aug-03-2017, 08:19 AM
RE: a suggestion for a feature change - by Skaperen - Aug-04-2017, 03:31 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  IDE suggestion JackMack118 5 3,313 Nov-21-2019, 11:35 PM
Last Post: JackMack118
  Need Suggestion for a Good Python IDE Aprogrammer 6 4,092 Aug-14-2018, 02:22 PM
Last Post: Aprogrammer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020