Dora
Dora

Reputation: 6970

how to pass optional parameters into a function in python?

I have a function which I want to pass two optional parameters. I have read through but somehow I am not able to make it work though.

What am I missing here?

I have something like this

def json_response_message(status, message, option_key, option_value):
    data = {
        'status': status,
        'message': message,
    }
    if option_key:
        data[option_key] = option_value
    return JsonResponse(data)

the last two parameters I want it to be optional.

I have seen there it can be done by doing

def json_response_message(status, message, option_key='', option_value=''):

but I don't really want to do it this way and saw that there is a way to pass *args and **kwargs but it couldn't get it to work though.

I am just stuck at putting the optional parameters but not sure how to call and use them. I read through some posts and its' easily be done and call by using a for loop but somehow it just didn't work for me

def json_response_message(status, message, *args, **kwargs):
    data = {
        'status': status,
        'message': message,
    }

    return JsonResponse(data)

I want add extra parameters into my data return such as...

    user = {
        'facebook': 'fb',
        'instagram': 'ig'
    }

    return json_response_message(True, 'found', 'user', user)

Upvotes: 0

Views: 650

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

You want something like this, I suppose:

def json_response_message(status, message, options=()):
    data = {
    'status': status,
    'message': message,
    }

    # assuming options is now just a dictionary or a sequence of key-value pairs
    data.update(options)

    return data

And you can use it like this:

user = {
    'facebook': 'fb',
    'instagram': 'ig'
}
print(json_response_message(True, 'found', user))

Upvotes: 2

Max Power
Max Power

Reputation: 8954

def json_response_message(status, message, *args):

    #input validation
    assert len(args) == 0 or len(args) == 2

    # add required params to data
    data = {
    'status': status,
    'message': message,
    }

    # add optional params to data if provided
    if args:
      option_key = args[0]
      option_value = args[1]
      data[option_key] = option_value      

    return data

print(json_response_message(True, 'found', 'user', user))

{'user': 'jim', 'status': True, 'message': 'found'}

Upvotes: 0

Related Questions