Why does this print `3 {}` and not `2 {'a': 3}`? - python

def f(a=2, **b):
print(a,b)
f(**{'a':3})
Why does this print 3 {} and not 2 {'a': 3}?
I can understand why it printed 3 {} if it was f(a=3) but I don't understand the output in this case.

The unpacking operator, when used on a dict, passes the dict's contents as keyword arguments.
In other words, the following two lines are functionally identical:
f(a=3)
f(**{'a':3})
Since a is getting passed explicitly as a keyword argument, the default value of 2 is overwritten. And since no other arguments are passed, the **b argument is left empty.

The call f(**{'a':3}) is same as f(a=3), so the value of a is 3 and not the default 2. For b , using the unpacking operator **, it means to save all the other mapping variable into it, as there is no one, it values an empty dict
a is 3
b is empty dict, {}
So it prints 3 {}
To use b you need to pass argument named differently as a
# both print: 3 {'foo': 'bar', 'number': 100}
f(**{'a':3, 'foo':'bar', 'number':100})
f(a=3, foo='bar', number=100)

Related

Why would you create a variable in a function call? [duplicate]

How are "keyword arguments" different from regular arguments? Can't all arguments be passed as name=value instead of using positional syntax?
There are two related concepts, both called "keyword arguments".
On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.
The other concept is on the function definition side: you can define a function that takes parameters by name -- and you don't even have to specify what those names are. These are pure keyword arguments, and can't be passed positionally. The syntax is
def my_function(arg1, arg2, **kwargs)
Any keyword arguments you pass into this function will be placed into a dictionary named kwargs. You can examine the keys of this dictionary at run-time, like this:
def my_function(**kwargs):
print str(kwargs)
my_function(a=12, b="abc")
{'a': 12, 'b': 'abc'}
There is one last language feature where the distinction is important. Consider the following function:
def foo(*positional, **keywords):
print "Positional:", positional
print "Keywords:", keywords
The *positional argument will store all of the positional arguments passed to foo(), with no limit to how many you can provide.
>>> foo('one', 'two', 'three')
Positional: ('one', 'two', 'three')
Keywords: {}
The **keywords argument will store any keyword arguments:
>>> foo(a='one', b='two', c='three')
Positional: ()
Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}
And of course, you can use both at the same time:
>>> foo('one','two',c='three',d='four')
Positional: ('one', 'two')
Keywords: {'c': 'three', 'd': 'four'}
These features are rarely used, but occasionally they are very useful, and it's important to know which arguments are positional or keywords.
Using keyword arguments is the same thing as normal arguments except order doesn't matter. For example the two functions calls below are the same:
def foo(bar, baz):
pass
foo(1, 2)
foo(baz=2, bar=1)
Positional Arguments
They have no keywords before them. The order is important!
func(1,2,3, "foo")
Keyword Arguments
They have keywords in the front. They can be in any order!
func(foo="bar", baz=5, hello=123)
func(baz=5, foo="bar", hello=123)
You should also know that if you use default arguments and neglect to insert the keywords, then the order will then matter!
def func(foo=1, baz=2, hello=3): ...
func("bar", 5, 123)
There are two ways to assign argument values to function parameters, both are used.
By Position. Positional arguments do not have keywords and are assigned first.
By Keyword. Keyword arguments have keywords and are assigned second, after positional arguments.
Note that you have the option to use positional arguments.
If you don't use positional arguments, then -- yes -- everything you wrote turns out to be a keyword argument.
When you call a function you make a decision to use position or keyword or a mixture. You can choose to do all keywords if you want. Some of us do not make this choice and use positional arguments.
I'm surprised that no one seems to have pointed out that one can pass a dictionary of keyed argument parameters, that satisfy the formal parameters, like so.
>>> def func(a='a', b='b', c='c', **kwargs):
... print 'a:%s, b:%s, c:%s' % (a, b, c)
...
>>> func()
a:a, b:b, c:c
>>> func(**{'a' : 'z', 'b':'q', 'c':'v'})
a:z, b:q, c:v
>>>
Using Python 3 you can have both required and non-required keyword arguments:
Optional: (default value defined for param 'b')
def func1(a, *, b=42):
...
func1(value_for_a) # b is optional and will default to 42
Required (no default value defined for param 'b'):
def func2(a, *, b):
...
func2(value_for_a, b=21) # b is set to 21 by the function call
func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`
This can help in cases where you have many similar arguments next to each other especially if they are of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.
I'm surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using *args and **kwargs (from this site):
def test_var_kwargs(farg, **kwargs):
print "formal arg:", farg
for key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])
This allows you to use arbitrary keyword arguments that may have keys you don't want to define upfront.
I was looking for an example that had default kwargs using type annotation:
def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
return ' '.join([a, b, c, str(kwargs)])
example:
>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}
Just suplement/add a way for defining the default value of arguments that is not assigned in key words when calling the function:
def func(**keywargs):
if 'my_word' not in keywargs:
word = 'default_msg'
else:
word = keywargs['my_word']
return word
call this by:
print(func())
print(func(my_word='love'))
you'll get:
default_msg
love
read more about *args and **kwargs in python: https://www.digitalocean.com/community/tutorials/how-to-use-args-and-kwargs-in-python-3

Difference call function with asterisk parameter and without

I know what the meaning of an asterisk is in a function definition in Python.
I often, though, see asterisks for calls to functions with parameters like:
def foo(*args, **kwargs):
first_func(args, kwargs)
second_func(*args, **kwargs)
What is the difference between the first and the second function call?
Let args = [1,2,3]:
func(*args) == func(1,2,3) - variables are unpacked out of list (or any other sequence type) as parameters
func(args) == func([1,2,3]) - the list is passed
Let kwargs = dict(a=1,b=2,c=3):
func(kwargs) == func({'a':1, 'b':2, 'c':3}) - the dict is passed
func(*kwargs) == func(('a','b','c')) - tuple of the dict's keys (in random order)
func(**kwargs) == func(a=1,b=2,c=3) - (key, value) are unpacked out of the dict (or any other mapping type) as named parameters
The difference is how the arguments are passed into the called functions. When you use the *, the arguments are unpacked (if they're a list or tuple)—otherwise, they're simply passed in as is.
Here's an example of the difference:
>>> def add(a, b):
... print a + b
...
>>> add(*[2,3])
5
>>> add([2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes exactly 2 arguments (1 given)
>>> add(4, 5)
9
When I prefixed the argument with *, it actually unpacked the list into two separate arguments, which were passed into add as a and b. Without it, it simply passed in the list as a single argument.
The same is the case for dictionaries and **, except they're passed in as named arguments rather than ordered arguments.
>>> def show_two_stars(first, second='second', third='third'):
... print "first: " + str(first)
... print "second: " + str(second)
... print "third: " + str(third)
>>> show_two_stars('a', 'b', 'c')
first: a
second: b
third: c
>>> show_two_stars(**{'second': 'hey', 'first': 'you'})
first: you
second: hey
third: third
>>> show_two_stars({'second': 'hey', 'first': 'you'})
first: {'second': 'hey', 'first': 'you'}
second: second
third: third
def fun1(*args):
""" This function accepts a non keyworded variable length argument as a parameter.
"""
print args
print len(args)
>>> a = []
>>> fun1(a)
([],)
1
# This clearly shows that, the empty list itself is passed as a first argument. Since *args now contains one empty list as its first argument, so the length is 1
>>> fun1(*a)
()
0
# Here the empty list is unwrapped (elements are brought out as separate variable length arguments) and passed to the function. Since there is no element inside, the length of *args is 0
>>>

Converting Python dict to kwargs?

I want to build a query for sunburnt(solr interface) using class inheritance and therefore adding key - value pairs together. The sunburnt interface takes keyword arguments. How can I transform a dict ({'type':'Event'}) into keyword arguments (type='Event')?
Use the double-star (aka double-splat?) operator:
func(**{'type':'Event'})
is equivalent to
func(type='Event')
** operator would be helpful here.
** operator will unpack the dict elements and thus **{'type':'Event'} would be treated as type='Event'
func(**{'type':'Event'}) is same as func(type='Event') i.e the dict elements would be converted to the keyword arguments.
FYI
* will unpack the list elements and they would be treated as positional arguments.
func(*['one', 'two']) is same as func('one', 'two')
Here is a complete example showing how to use the ** operator to pass values from a dictionary as keyword arguments.
>>> def f(x=2):
... print(x)
...
>>> new_x = {'x': 4}
>>> f() # default value x=2
2
>>> f(x=3) # explicit value x=3
3
>>> f(**new_x) # dictionary value x=4
4

Assigning to a dict

Forgive me if this has been asked before. I did not know how to search for it.
I'm quite familiar with the following idiom:
def foo():
return [1,2,3]
[a,b,c] = foo()
(d,e,f) = foo()
wherein the values contained within the left hand side will be assigned based upon the values returned from the function on the right.
I also know you can do
def bar():
return {'a':1,'b':2,'c':3}
(one, two, three) = bar()
[four, five, six] = bar()
wherein the keys returned from the right hand side will be assigned to the containers on the left hand side.
However, I'm curious, is there a way to do the following in Python 2.6 or earlier:
{letterA:one, letterB:two, letterC:three} = bar()
and have it work in the same manner that it works for sequences to sequences? If not, why? Naively attempting to do this as I've written it will fail.
Dictionary items do not have an order, so while this works:
>>> def bar():
... return dict(a=1,b=2,c=3)
>>> bar()
{'a': 1, 'c': 3, 'b': 2}
>>> (lettera,one),(letterb,two),(letterc,three) = bar().items()
>>> lettera,one,letterb,two,letterc,three
('a', 1, 'c', 3, 'b', 2)
You can see that you can't necessarily predict how the variables will be assigned. You could use collections.OrderedDict in Python 3 to control this.
If you modify bar() to return a dict (as suggested by #mikerobi), you might want to still preserve keyed items that are in your existing dict. In this case, use update:
mydict = {}
mydict['existing_key'] = 100
def bar_that_says_dict():
return { 'new_key': 101 }
mydict.update(bar_that_says_dict())
print mydict
This should output a dict with both existing_key and new_key. If mydict had a key of new_key, then the update would overwrite it with the value returned from bar_that_says_dict.
No, if you can not change bar function, you could create a dict from the output pretty easily.
This is the most compact solution. But I would prefer to modify the bar function to return a dict.
dict(zip(['one', 'two', 'three'], bar()))

Normal arguments vs. keyword arguments

How are "keyword arguments" different from regular arguments? Can't all arguments be passed as name=value instead of using positional syntax?
There are two related concepts, both called "keyword arguments".
On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.
The other concept is on the function definition side: you can define a function that takes parameters by name -- and you don't even have to specify what those names are. These are pure keyword arguments, and can't be passed positionally. The syntax is
def my_function(arg1, arg2, **kwargs)
Any keyword arguments you pass into this function will be placed into a dictionary named kwargs. You can examine the keys of this dictionary at run-time, like this:
def my_function(**kwargs):
print str(kwargs)
my_function(a=12, b="abc")
{'a': 12, 'b': 'abc'}
There is one last language feature where the distinction is important. Consider the following function:
def foo(*positional, **keywords):
print "Positional:", positional
print "Keywords:", keywords
The *positional argument will store all of the positional arguments passed to foo(), with no limit to how many you can provide.
>>> foo('one', 'two', 'three')
Positional: ('one', 'two', 'three')
Keywords: {}
The **keywords argument will store any keyword arguments:
>>> foo(a='one', b='two', c='three')
Positional: ()
Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}
And of course, you can use both at the same time:
>>> foo('one','two',c='three',d='four')
Positional: ('one', 'two')
Keywords: {'c': 'three', 'd': 'four'}
These features are rarely used, but occasionally they are very useful, and it's important to know which arguments are positional or keywords.
Using keyword arguments is the same thing as normal arguments except order doesn't matter. For example the two functions calls below are the same:
def foo(bar, baz):
pass
foo(1, 2)
foo(baz=2, bar=1)
Positional Arguments
They have no keywords before them. The order is important!
func(1,2,3, "foo")
Keyword Arguments
They have keywords in the front. They can be in any order!
func(foo="bar", baz=5, hello=123)
func(baz=5, foo="bar", hello=123)
You should also know that if you use default arguments and neglect to insert the keywords, then the order will then matter!
def func(foo=1, baz=2, hello=3): ...
func("bar", 5, 123)
There are two ways to assign argument values to function parameters, both are used.
By Position. Positional arguments do not have keywords and are assigned first.
By Keyword. Keyword arguments have keywords and are assigned second, after positional arguments.
Note that you have the option to use positional arguments.
If you don't use positional arguments, then -- yes -- everything you wrote turns out to be a keyword argument.
When you call a function you make a decision to use position or keyword or a mixture. You can choose to do all keywords if you want. Some of us do not make this choice and use positional arguments.
I'm surprised that no one seems to have pointed out that one can pass a dictionary of keyed argument parameters, that satisfy the formal parameters, like so.
>>> def func(a='a', b='b', c='c', **kwargs):
... print 'a:%s, b:%s, c:%s' % (a, b, c)
...
>>> func()
a:a, b:b, c:c
>>> func(**{'a' : 'z', 'b':'q', 'c':'v'})
a:z, b:q, c:v
>>>
Using Python 3 you can have both required and non-required keyword arguments:
Optional: (default value defined for param 'b')
def func1(a, *, b=42):
...
func1(value_for_a) # b is optional and will default to 42
Required (no default value defined for param 'b'):
def func2(a, *, b):
...
func2(value_for_a, b=21) # b is set to 21 by the function call
func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`
This can help in cases where you have many similar arguments next to each other especially if they are of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.
I'm surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using *args and **kwargs (from this site):
def test_var_kwargs(farg, **kwargs):
print "formal arg:", farg
for key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])
This allows you to use arbitrary keyword arguments that may have keys you don't want to define upfront.
I was looking for an example that had default kwargs using type annotation:
def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
return ' '.join([a, b, c, str(kwargs)])
example:
>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}
Just suplement/add a way for defining the default value of arguments that is not assigned in key words when calling the function:
def func(**keywargs):
if 'my_word' not in keywargs:
word = 'default_msg'
else:
word = keywargs['my_word']
return word
call this by:
print(func())
print(func(my_word='love'))
you'll get:
default_msg
love
read more about *args and **kwargs in python: https://www.digitalocean.com/community/tutorials/how-to-use-args-and-kwargs-in-python-3

Categories

Resources