PYTHON

Create Immutable, Hashable Sets with Python Frozenset

Learn how to use Python's frozenset to create immutable sets that can be used as dictionary keys or elements in other sets, ideal for caching based on set conditions.

def calculate_permissions(user_roles):
    """
    Determines effective permissions based on a frozenset of user roles.
    Uses a cache for performance.
    """
    # A dictionary to cache permissions for specific role combinations
    # frozenset is used as the key because regular sets are unhashable
    _permission_cache = {}

    # Define some base permissions for roles
    ROLE_PERMISSIONS = {
        'admin': frozenset(['view_dashboard', 'manage_users', 'edit_content']),
        'editor': frozenset(['edit_content', 'upload_media']),
        'viewer': frozenset(['view_content']),
        'guest': frozenset(['view_public_content'])
    }

    roles_frozenset = frozenset(user_roles)

    if roles_frozenset in _permission_cache:
        print(f"Cache hit for roles: {user_roles}")
        return _permission_cache[roles_frozenset]

    print(f"Calculating permissions for roles: {user_roles}")
    effective_permissions = frozenset()
    for role in roles_frozenset:
        effective_permissions = effective_permissions.union(ROLE_PERMISSIONS.get(role, frozenset()))

    _permission_cache[roles_frozenset] = effective_permissions
    return effective_permissions

# Example usage for a web application scenario
admin_perms = calculate_permissions(['admin', 'editor'])
print("Admin+Editor Permissions:", sorted(list(admin_perms)))

viewer_perms = calculate_permissions(['viewer'])
print("Viewer Permissions:", sorted(list(viewer_perms)))

# Calling with the same roles should result in a cache hit
admin_editor_perms_cached = calculate_permissions(['editor', 'admin']) # Order doesn't matter for sets
print("Admin+Editor Permissions (cached):", sorted(list(admin_editor_perms_cached)))

guest_perms = calculate_permissions(['guest'])
print("Guest Permissions:", sorted(list(guest_perms)))
How it works: `frozenset` is an immutable version of Python's built-in `set`. Unlike regular sets, frozensets are hashable, meaning they can be used as keys in dictionaries or as elements in other sets. This snippet demonstrates using `frozenset` for caching calculated permissions based on a user's roles, ensuring that the combination of roles can serve as a reliable and efficient cache key.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs