How to Find the Intersection of Permission Sets in Python
This code defines a function that takes a list of permission sets and returns a set containing only the permissions common to all sets, with a short-circuit for empty results.
Python code
24 linesfrom typing import Set
def intersect_permissions(permission_sets: list[Set[str]]) -> Set[str]:
"""
Given a list of permission sets, return the common permissions
present in every set.
"""
if not permission_sets:
return set()
common = permission_sets[0]
for perm_set in permission_sets[1:]:
common = common.intersection(perm_set)
if not common:
break
return common
if __name__ == "__main__":
admin_perms = {"read", "write", "delete", "execute"}
editor_perms = {"read", "write", "edit"}
viewer_perms = {"read", "view"}
result = intersect_permissions([admin_perms, editor_perms, viewer_perms])
print(f"Common permissions: {sorted(result)}")
Output
Common permissions: ['read']
How it works
The function starts by checking if the input list is empty, returning an empty set to avoid an IndexError. It initializes common with the first set and then iterates over the remaining sets, updating common with the intersection of itself and the current set. Using set.intersection returns a new set containing elements present in both sets. The early break when common becomes empty optimizes performance by stopping the loop once no common permissions remain. The type hints with Set[str] clarify that the function works with sets of strings, and the example in the __main__ block demonstrates typical usage.
Common mistakes
- Forgetting to handle the empty list case, which raises an IndexError
- Modifying the original sets by using `intersection_update` instead of `intersection`
- Assuming order of set elements, which is not guaranteed in Python
Variations
- Use `functools.reduce(set.intersection, permission_sets)` for a concise one-liner
- Use the `&` operator: `common &= perm_set` for in-place intersection
Real-world use cases
- Checking which API endpoints a group of users with different roles can all access.
- Finding common file permissions across multiple user groups in a shared filesystem.
- Determining overlapping feature flags enabled across all environments in a deployment config.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.