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
3
  • 1
    That's not a positional argument, that's a keyword argument—the exact opposite kind. Commented Aug 3, 2018 at 0:04
  • @abarnert Yes, you're right. I forgot it's more specific case, I'll edit in a moment. Commented Aug 3, 2018 at 0: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. Commented Aug 3, 2018 at 0:09

1 Answer 1

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'})
Sign up to request clarification or add additional context in comments.

1 Comment

This is a bad code smell.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.