Passing List of Named Parameters to Function

Passing list of named parameters to function?

Almost there: try

do.call(runif,c(list(n=100),params)) 

Your variant, list(n=100,params) makes a list where the second element is your list of parameters. Use str() to compare the structure of list(n=100,params) and c(list(n=100),params) ...

Passing arguments to a function with named arguments

What you are doing now is simply passing a set to slave as a single argument. So you're probably getting a TypeError on a positional argument missing.

You might want to change your slave_work to be a dict (right now it is a set), and then it would look like:

slave_work = {'func': my_func, 'args': {'a': 50, 'b': 90}}

And now you can unpack the dict by doing:

print(slave(**slave_work))

This is more or less equivalent for doing:

print(slave(func=slave_work['func'], args=slave_work['args'])

Then inside your slave function change accordingly to:

result = func(**args)

Another option is to use list (or tuple in this case) unpacking. So your slave_work can also be:

slave_work = {'func': my_func, 'args': (50, 90)}

And then your call to slave will be the same, but inside slave change to:

result = func(*args)

The difference is that this will unpack the arguments according to their position and not their name.

Passing a list of named parameters with NULL value to a function

This should be find if you use c() but make sure your first parameter is a list

my_func <- function(df, ..., .f = sum, args = NULL) {
df %>%
dplyr::bind_rows(
dplyr::summarize_at(., dplyr::vars(...), ~do.call(.f, c(list(.x), args)))
)
}

how to pass named parameters to function in python

You can call A with the keyword argument that you need. In a similar case i put the arguments from the calling function in a dict and pass his to the called function

def A(p1 = 0, p2 = 0):
print(str(p1) + str(p2))
def B(par_name, par_val):
para_dict = dict()
para_dict[para_name] = para_val
A(**para_dict)

Please see Key Word Arguments in the python docs for more details.

another way is, that your dict already has all keys p1, p2 with its default values and you are just update the key you want and pass it to A

para_dict = {"p1":0,"p2":0}

and it might be better to loop through the arguments in A

Is there a way to provide named parameters in a function call in JavaScript?

ES2015 and later

In ES2015, parameter destructuring can be used to simulate named parameters. It would require the caller to pass an object, but you can avoid all of the checks inside the function if you also use default parameters:

myFunction({ param1 : 70, param2 : 175});

function myFunction({param1, param2}={}){
// ...function body...
}

// Or with defaults,
function myFunc({
name = 'Default user',
age = 'N/A'
}={}) {
// ...function body...
}

ES5

There is a way to come close to what you want, but it is based on the output of Function.prototype.toString [ES5], which is implementation dependent to some degree, so it might not be cross-browser compatible.

The idea is to parse the parameter names from the string representation of the function so that you can associate the properties of an object with the corresponding parameter.

A function call could then look like

func(a, b, {someArg: ..., someOtherArg: ...});

where a and b are positional arguments and the last argument is an object with named arguments.

For example:

var parameterfy = (function() {
var pattern = /function[^(]*\(([^)]*)\)/;

return function(func) {
// fails horribly for parameterless functions ;)
var args = func.toString().match(pattern)[1].split(/,\s*/);

return function() {
var named_params = arguments[arguments.length - 1];
if (typeof named_params === 'object') {
var params = [].slice.call(arguments, 0, -1);
if (params.length < args.length) {
for (var i = params.length, l = args.length; i < l; i++) {
params.push(named_params[args[i]]);
}
return func.apply(this, params);
}
}
return func.apply(null, arguments);
};
};
}());

Which you would use as:

var foo = parameterfy(function(a, b, c) {
console.log('a is ' + a, ' | b is ' + b, ' | c is ' + c);
});

foo(1, 2, 3); // a is 1 | b is 2 | c is 3
foo(1, {b:2, c:3}); // a is 1 | b is 2 | c is 3
foo(1, {c:3}); // a is 1 | b is undefined | c is 3
foo({a: 1, c:3}); // a is 1 | b is undefined | c is 3

DEMO

There are some drawbacks to this approach (you have been warned!):

  • If the last argument is an object, it is treated as a "named argument objects"
  • You will always get as many arguments as you defined in the function, but some of them might have the value undefined (that's different from having no value at all). That means you cannot use arguments.length to test how many arguments have been passed.

Instead of having a function creating the wrapper, you could also have a function which accepts a function and various values as arguments, such as

call(func, a, b, {posArg: ... });

or even extend Function.prototype so that you could do:

foo.execute(a, b, {posArg: ...});

Can I call function in python with named arguments as a variable?

You can pass a dictionary of keywords arguments to a function using the ** operator. The keys of the dictionary are the parameter names in the function.

In this case, that could be:

get_user_by(**{username_type: username})

If the variable username_type has the value 'email' then the username would be received in get_user_by as the keyword argument email.

Pass named parameter to a method

Java does not have named arguments, just positional arguments. You need to pass it without the parameter's name:

a.changeTheHueOfTheColor(1);
// Here -----------------^

Why can I pass a list of named arguments -- but not unnamed arguments -- to this decorator?

def my_decorator(self, *args, **kwargs):
[skip]
if 'func' in kwargs:
return inner_function(kwargs.pop('func'))
else:
return inner_function


Related Topics



Leave a reply



Submit