0

I spent some time to figure that out, so I post this Q&A. Let's say you have function def my_func(group) which takes an argument group which will be used as positional argument in next function: def set_permission(group_user=None, group_admin=None). So:

group = 'group_user'
my_func(group):
  if group == 'group_user':
    set_permission(group_user='write')
  if group == 'group_admin':
    set_permission(group_admin='write')

but what if group can be 20 combinations?

And more 'real' case from Django:

from models import User, Project
import mommy

def create_instance_of_repetable_model(model, model_field):
  if model == User:
    mommy.make(User, user_perm='write')
  if model == Project:
    mommy.make(Project, project_perm='write')
  if model == Project
Qback
  • 4,310
  • 3
  • 25
  • 38
  • 1
    That's not a positional argument, that's a keyword argument—the exact opposite kind. – abarnert Aug 03 '18 at 00:04
  • @abarnert Yes, you're right. I forgot it's more specific case, I'll edit in a moment. – Qback Aug 03 '18 at 00:08
  • If you're writing the function yourself, you should give it the API that you actually want to call, not an API that's painful to call so you have to hack your way around it. – abarnert Aug 03 '18 at 00:09

1 Answers1

2

As found in official python docs:

group = 'group_user'
def my_func(group):
  set_permission(**{group: 'write'})  # it works like set_permission(group_user='write')
  print_permission(group)

my_func(group)  #  prints -> 'group_user': 'write'

group = 'group_admin'
my_func(group)  # prints -> 'group_admin': 'write'

and 'real life'

from models import User, Project
import mommy

def create_instance_of_repetable_model(model, model_field):
  mommy.make(model, **{model_field: 'write'})
Qback
  • 4,310
  • 3
  • 25
  • 38