A permissions manager revokes a permission that might already have been removed.
What You Need to Understand
set.remove(value) raises KeyError when the value is absent, while set.discard(value) silently does nothing. Choose whether absence should be treated as an error or as normal behavior.
When to Use It
A permissions manager revokes a permission that might already have been removed.
Step-by-Step Python Example
permissions = {"read", "write"}
permissions.discard("admin")
print(sorted(permissions))
try:
permissions.remove("admin")
except KeyError:
print("Permission was not present")
How the Example Works
The discard call succeeds without changing the set; the remove call raises the specific error that the example handles.
Example Output
['read', 'write']
Permission was not present
False
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
def delete_if_present(values, item):
existed = item in values
values.discard(item)
return existed
print(delete_if_present({1, 2}, 3))
Important Behavior and Edge Cases
Avoid hiding unexpected missing values if they indicate incorrect state. discard() returns None, not a success flag.
Try It Yourself
Write a small helper that returns whether a membership was actually removed.
Common Beginner Mistakes
- Avoid hiding unexpected missing values if they indicate incorrect state.
discard()returnsNone, not a success flag. - Applying the example without a clearly defined policy for missing keys, matching identifiers, or validating external values.
Key Takeaways
set.remove(value)raisesKeyErrorwhen the value is absent, whileset.discard(value)silently does nothing.- The discard call succeeds without changing the set; the remove call raises the specific error that the example handles.
- Avoid hiding unexpected missing values if they indicate incorrect state.