variadic-functions

Why does passing a dictionary as part of *args give us only the keys?

Why does passing a dictionary as part of *args give us only the keys? Question: The setup Let’s say I have a function: def variadic(*args, **kwargs): print("Positional:", args) print("Keyword:", kwargs) Just for experiment’s sake, I call it with the following: variadic({‘a’:5, ‘b’:’x’}, *{‘a’:4, ‘b’:’y’}, **{‘a’:3, ‘b’:’z’}) Output: Positional: ({‘a’: 5, ‘b’: ‘x’}, ‘a’, ‘b’) Keyword: …

Total answers: 1

Passing a list of parameters into a Python function

Passing a list of parameters into a Python function Question: How would I pass an unknown number of parameters into a function? I have a function defined in the following way def func(x, *p): # do something with variable number of parameters (*p) pass I’m trying to pass in a list of values to use …

Total answers: 2

Why is foo(*arg, x) not allowed in Python?

Why is foo(*arg, x) not allowed in Python? Question: Look at the following example point = (1, 2) size = (2, 3) color = ‘red’ class Rect(object): def __init__(self, x, y, width, height, color): pass It would be very tempting to call: Rect(*point, *size, color) Possible workarounds would be: Rect(point[0], point[1], size[0], size[1], color) Rect(*(point …

Total answers: 5

Python, default keyword arguments after variable length positional arguments

Python, default keyword arguments after variable length positional arguments Question: I thought I could use named parameters after variable-length positional parameters in a function call in Python 2, but I get a SyntaxError when importing a python class. I’m writing with the following “get” method, for example: class Foo(object): def __init__(self): print “You have created …

Total answers: 2

varargs in lambda functions in Python

varargs in lambda functions in Python Question: Is it possible a lambda function to have variable number of arguments? For example, I want to write a metaclass, which creates a method for every method of some other class and this newly created method returns the opposite value of the original method and has the same …

Total answers: 3

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

What does ** (double star/asterisk) and * (star/asterisk) do for parameters? Question: What do *args and **kwargs mean in these function definitions? def foo(x, y, *args): pass def bar(x, y, **kwargs): pass See What do ** (double star/asterisk) and * (star/asterisk) mean in a function call? for the complementary question about arguments. Asked By: Todd …

Total answers: 27