Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Misunderstanding kwargs?
#2
def test(*args, **kvargs):
    print(type(args), args, type(kvargs), kvargs)

test('this', 'is', a='a', test='test')
test(*('this', 'is'), **{'a':'a', 'test':'test'})
Output:
<class 'tuple'> ('this', 'is') <class 'dict'> {'a': 'a', 'test': 'test'} <class 'tuple'> ('this', 'is') <class 'dict'> {'a': 'a', 'test': 'test'}
So args is a tuple and kvargs is a dictionary.
*(1, 2, 3) extracts the values from the tuple and provides them as separate items instead of a collection. This is called "unpacking". You can also unpack a dictionary though what is returned is less obvious.

You don't have to understand how kvargs works to use it. Even though kvargs is a dictionary you should not be treating it as a dictionary. To extract values from *args and **kvargs you specify arguments for your function:
def leftovers(*args, **kvargs):
    print(args, kvargs)

def filter(a, *args, b='thing', **kvargs):
    leftovers(*args, **kvargs)

filter(1, 2, b=3, c=4)
Output:
(2,) {'c': 4}
The function "filter" consumes the first position argument and the 'b' keyword argument. The remaining arguments can be passed on to the "leftovers" function. This is so much simpler than:
def leftovers(*args, **kvargs):
    print(args, kvargs)

def filter(*args, **kvargs):
    a = args[0]
    b = kvargs['b']
    del kvargs['b']
    leftovers(args[1:], **kvargs)

filter(1, 2, b=3, c=4)
Reply


Messages In This Thread
Misunderstanding kwargs? - by Donovan - Aug-04-2020, 06:06 PM
RE: Misunderstanding kwargs? - by deanhystad - Aug-04-2020, 07:01 PM
RE: Misunderstanding kwargs? - by Donovan - Aug-04-2020, 08:09 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I instantiate a class with **kwargs? palladium 6 8,160 Feb-16-2023, 06:10 PM
Last Post: deanhystad
  kwargs question Jeff_t 8 3,324 Feb-16-2022, 04:33 PM
Last Post: Jeff_t
  **kwargs question DPaul 10 4,691 Apr-01-2020, 07:52 AM
Last Post: buran
  Unpacking dictionary from .xlsx as Kwargs etjkai 5 3,047 Dec-27-2019, 05:31 PM
Last Post: etjkai
  opts vs kwargs Skaperen 4 2,635 Nov-30-2019, 04:57 AM
Last Post: Skaperen
  misunderstanding of format in print function Harvey 2 2,284 Oct-29-2019, 12:44 PM
Last Post: buran
  Simple list comprehension misunderstanding Mark17 3 2,698 Oct-10-2019, 07:00 PM
Last Post: buran
  Bug or my misunderstanding? MrSteveVee 2 3,626 Jan-04-2018, 10:58 PM
Last Post: MrSteveVee
  Misunderstanding with the “if” statement and “not equal” scriptoghost 6 4,611 Jun-23-2017, 09:43 AM
Last Post: DeaD_EyE
  create dictionary from **kwargs that include tuple bluefrog 2 5,061 Oct-26-2016, 10:24 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020