Functions

Defining

def func_id():
suite
def func_id(param_list):
suite

Calling

func_id()
func_id(param_list)

Arguments

  • Parentheses are required, even when there are no parameters.
  • Args are passed by value.
  • Only args representing a mutable object can be modified (are inout parameters).

Argument types

id
id = default_value
*id A tuple of all remaining args (like C vararg).
**id A dictionary of all extra arguments passed as keywords.

Default arguments

  • Default arg values are evaluated once, when the function is defined.
# Unintended behavior.
i = 5
def f(arg=i):
print arg

i = 6
f() # will print 5
# Workaround solution, using None as the default value.
i = 5
def f(arg=None):
if arg is None:
arg=i
print arg

i = 6
f() # will print 6

Keyword arguments

  • Any keyword parameters used when calling a function must be after any positional parameters.
def test(param1, param2="beta", *rest, **keywords):
print param1, param2

test("one", "two")
test("alpha")
test("un", param2="deux")

Return values

  • A function can optionally return a value.
  • Use a tuple to return more than one value.