Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally passing a named keyword argument to a function [duplicate]

Tags:

python

I'm not sure if I'm using the correct wording in my question but the situation I have is that I'm calling a function and passing a value to one of its named keyword arguments only if I have a value for it. A simplified example of how I'm currently doing it:

var_1 = data.get("var_1", None)

if var_1:
    some_function(some_arg=var_1)
else:
    some_function()

The function some_function() does not accept setting some_arg to None so I can only call the function with the named argument if I have a valid value for it.

The reason why the above is less desirable for me is that the actual function calls I'm making have a bunch (5+) of named arguments that I set. This results in repeating mostly similar function calls that differ by only one parameter.

Is there a better way/more Pythonic way to do this? I wish I could call the function and set all possible named parameters that I might wish to pass but, at runtime, only pass in the values that I actually have something for.

In case it matters, the function calls are to the AWS Python SDK (Boto3) so I can't alter the behavior of the function.

like image 541
swigganicks Avatar asked May 09 '18 16:05

swigganicks


People also ask

Does Python pass by reference or Copy?

Python passes arguments neither by reference nor by value, but by assignment.

How do you pass an argument from one function to another in python?

I would expect this to do as follows: Initialize 'list' as an empty list; call main (this, at least, I know I've got right...) Within defineAList(), assign certain values into the list; then pass the new list back into main() Within main(), call useTheList(list)

What is Arbitrary argument?

Python Arbitrary Arguments allows a function to accept any number of positional arguments i.e. arguments that are non-keyword arguments, variable-length argument list.

How do you send args in Python?

Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.


1 Answers

What you can do is:

var_1 = data.get("var_1", None)
fun_kwargs = {'some_arg': var_1} if var_1 else {}
some_function(**fun_kwargs)

If you have multiple parameters you could do:

fun_kwargs = {}
if var1: fun_kwargs['some_arg1'] = var_1
if var2: fun_kwargs['some_arg2'] = var_2
if var3: fun_kwargs['some_arg3'] = var_3
some_function(**fun_kwargs)
like image 185
jdehesa Avatar answered Sep 29 '22 20:09

jdehesa