Aemyl Aemyl - 1 year ago 136
Python Question

'Undefined' parameters in function calls in python

Whenever I program something in python with

, the code looks like this:

from Tkinter import *

class GUI():

def __init__(self, master):

self.master = master # master is an instance of Tk
self.master.title("") # set the name of the window

self.frame = Frame(self.master, width=800, height=500, bg="#eeeeee")
# 800, 500 and "#eeeeee" are examples of course

self.canvas = Canvas(self.frame, width=800, height=500, bg="ffffff"), y=0)
#mostly there are some other widgets

# here are obviously other methods

def main():

root = Tk()
app = GUI(root) # root and app.master are synonyms now

if __name__ == '__main__':


My problem is, I don't really understand why
Frame(width=800, height=500)
place(x=0, y=0)
is working: I didn't define the parameters
. Looking at the code in the
- module, the functions expect a paramter called
. I know how to use them (at least well enough to develop some small applications), but I don't know how to define a function which uses this parameters. I feel like I don't know really much about this part of python, though I can work with it.

So my Question is:

how can I define a function, what is called with the following Syntax:

functionName(parameterName1 = value, paramterName2 = value, ...)

I don't need to know how to make a function what accepts a varying amount of parameters (combined with my problem), but it would be fine too.

Answer Source

What you are referring to are called keyword arguments.

Arguably one of the best ways to define a function with specific keyword arguments is to provide defaults. It's common for the default to be None if you don't have the need for any other default:

def functionName(parameterName1=None, parameterName2=None):
    print("parameter one is: %s" % str(parameterName1))
    print("parameter two is: %s" % str(parameterName2))

You can then call this function like so:

foo = functionName(parameterName1="hello", parameterName2="world")

You can also do what tkinter functions do, and accept **kwargs as a parameter. This gathers up all named arguments into a dictionary that you can then iterate over:

def functionName(**kwargs):
    print("the arguments are:", kwargs)

Note: you don't have to use the name kwargs -- you can use any name you want (**kw, **kwargs, **whatever), but kwargs seems to be the most common.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download