Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
pop methods
#1
/of all the types/classes that have a pop() method, it seems only dict/pop() implements an optional 2nd argument for default. why is it limited to just dict.pop()
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Which classes should also have a default argument?
buran likes this post
Reply
#3
If you change the behavior of pop, you'll break all existing code.
You can inherit from UserList a make your own special type.
The point is, that a dict has key-values, where the pop method must access explicit a key.
The pop of sequences is different. It takes the last value from the list, if no argument is supplied.
Otherwise, it will return the element with the given index.

from collections import UserList


class DefaultPop(UserList):
    def pop(self, index=-1, default=None):
        try:
            return super().pop(index)
        except IndexError:
            return default


my_list = DefaultPop([1,2,3])


while True:
    value = my_list.pop(default=42)
    print(value)
    if value == 42:
        break
In collections, you've UserDict, UserList and UserString for inheritance.
Don't try this with dict, list and str. Often this won't work as expected.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
(Nov-19-2020, 09:22 AM)Gribouillis Wrote: Which classes should also have a default argument?

how about list and set.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#5
what code has a 2nd argument that it expects to provide something other than a default value for list and set?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

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