0

I'm a beginner in python, from the code below I found on twitter

how would you relegate the frozenset values to each of the set value to get the desired output? shoud the output not be a frozenset?

    admin_permissions = frozenset(['view', 'edit', 'delete', 'add'])
    editor_permissions = frozenset(['view', 'edit', 'add','deny'])
    viewer_permissions = frozenset(['view'])
    
    admins = {'Alice', 'Bob'}
    editors = {'Bob', 'Charlie', 'Dave'}
    viewers = {'Eve', 'Frank', 'Alice'}
    
    user_permissions = {}
    for user in admins:
        user_permissions[user] = admin_permissions
    for user in editors:
        user_permissions.setdefault(user, frozenset()).union(editor_permissions)
    for user in viewers:
        user_permissions.setdefault(user, frozenset()).union(viewer_permissions)
    
    print(user_permissions)

output is

{'Bob': frozenset({'edit', 'add', 'delete', 'view'}),
 'Alice': frozenset({'edit', 'add', 'delete', 'view'}),
 'Dave': frozenset(), 
 'Charlie': frozenset(), 
 'Frank': frozenset(), 
 'Eve': frozenset()
}

desired output

{'Bob': frozenset({'edit', 'add', 'delete', 'view', 'deny'}),
 'Alice': frozenset({'edit', 'add', 'delete', 'view'}),
 'Dave': frozenset({'edit', 'add', 'view', 'deny'}), 
 'Charlie': frozenset({'edit', 'add', 'view', 'deny'}), 
 'Frank': frozenset({'view'}), 
 'Eve': frozenset({'view'})
}
k1dr0ck
  • 1,043
  • 4
  • 13
  • 1
    *"isnt frozenset immutable why does the union works with a frozenset"* — Because `union` produces a _new_ set, it doesn't modify the set in place. And you're not doing anything with that new set, so Dave et al only have the default empty set. – deceze Aug 28 '23 at 00:25
  • @deceze with Bob as admin and editor aren't they combining permissions? im trying to understand the line i higlighted at the top of my post – k1dr0ck Aug 28 '23 at 00:34
  • 1
    You are thinking that the `union` function modifies one of the sets involved. It does not do so. It returns a NEW set, which you are discarding. – Tim Roberts Aug 28 '23 at 00:34
  • You'll need to assign the result of `union` to something: `user_permissions[user] = user_permissions.get(user, frozenset()).union(editor_permissions)`. – deceze Aug 28 '23 at 00:59

0 Answers0