2020
2020

Reputation: 2841

Why dict.popitem() raises KeyError instead of returning None?

Is there any benefit in dict.popitem() raising aKeyError exception when the dictionary is empty, instead of returning None (which is equivalent to Null) ?

my_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}

while True:
    try:
        item = my_dict.popitem()
        print(f'{item} removed')
        # process the item here...
    except KeyError:
        print('The dictionary is empty !')
        break

Or is raising an exception instead of returning None considered more pythonic ?

Upvotes: 0

Views: 1387

Answers (1)

Artyer
Artyer

Reputation: 40891

For this specific method, it is normally used like this:

k, v = my_dict.popitem()

Which currently raises a KeyError when the dict is empty, and would be a TypeError if it had instead returned None.

Raising a KeyError would mean writing this:

try:
    k, v = my_dict.popitem()
except KeyError:
    # Dictionary is empty
else:
    # Process k, v

# Or

if my_dict:
    k, v = my_dict.popitem()
    # Process k, v
else:
    # Dictionary is empty

And returning None:

item = my_dict.popitem()
if item is not None:
    k, v = item
    # Process k, v
else:
    # Dictionary is empty

If the method returned None, you have to acknowledge the fact that the dictionary might be empty or get the cryptic TypeError that means less, whereas the KeyError is much more clear.


Raising an error can also show that that's not normally what happens. If you instead wrote something like this:

def do_stuff(my_dict):
    """Process an item from a dictionary (It must not be empty)"""
    k, v = my_dict.popitem()
    # do stuff

An appropriate error would be raised.


It can easily be implemented like this though:

item = my_dict.popitem() if my_dict else None

Upvotes: 3

Related Questions