class Frame(Widget):
    def __init__(self, master=None, cnf={}, **kw):

what is the meaning of **kw in this function, and what does it represent?

4 Years
Discussion Span
Last Post by dashing.adamhughes

This is sort of buried in the language reference. If you look here: Click Here, it gets explained, but you have to dig. In particular:

or passed as a value in a dictionary preceded by **

That means that the identifier after the "**" is a dictionary with "variable name: value" entries.

Edited by rrashkin


The key word argument **kw indicates a dictionary of variable number of key:val arguments

Used when the number of arguments is not known ahead of time, an example ...

def make_dic(**kw):
    print(vars())  # show local dictionary
    return kw

d = make_dic(dg='dog', bw='bow', ct='cat')

''' result ...
{'kw': {'dg': 'dog', 'bw': 'bow', 'ct': 'cat'}}
{'dg': 'dog', 'bw': 'bow', 'ct': 'cat'}

Edited by vegaseat


A little more about *args and **kwargs

First vehicle take only 'car' as agument.
Next *args take 'hello', 'world' and make it a tuple.
Next **kwargs take key_a='value 1', key_b='value 2' and make it a dictionary.

def func(vehicle, *args, **kwargs):
    #argument vehicle
    print(vehicle) #--> car

    #argument *args
    print(args) #--> ('hello', 'world')
    print(args[1]) #--> world

    #argument **kwargs
    print(kwargs) #--> {'key_b': 'value 2', 'key_a': 'value 1'}
    print(kwargs['key_a']) #--> value 1

func('car', 'hello', 'world', key_a='value 1', key_b='value 2')

*args can take many arguments.

def bar(*args):
    print(sum(args)) #--> 45


**kwargs can take many arguments.
So here iterate over dictionary and print key --> value.

def foo(**kwargs):
    for key in kwargs:
        print("Values from dict--> {}: {}".format(key, kwargs[key]))

foo(Name='Zara', Age=7, Class='first')

Values from dict--> Age: 7
Values from dict--> Name: Zara
Values from dict--> Class: first

Edited by snippsat


Thanks guy for the indept explanation.
in short:
arg = is used to pass in an argument on size 1
*arg = is used to pass in argument of any size more than 0
**arg = is used to pass in a dict of size more than 0

thanks once again
by the way @snippsat i love your 3d works they are nice


I don't if I'd think about them in terms of sizes...

arg = required arguments of the function. Function will error without them.
*args = Additional non-keyword arguments that are not required for function to run.
**kwargs = additional keyword arguments that are not required.

*args and **kwargs are options.

Edited by dashing.adamhughes

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.