Search notes:

Python: statement def

def defines a user defined function object.

Function without arguments

#!/usr/bin/python3

def F0():
    print ('in F0')


F0()
# in F0

# The function needs to be called with the
# paranthesis: The following line does not
# invoke the function.
F0
Github repository about-python, path: /statements/def/no-arguments.py

Function with arguments

#!/usr/bin/python3

def F_args(a, b, c):
    print(''               )
    print('  a = ' + str(a))
    print('  b = ' + str(b))
    print('  c = ' + str(c))

F_args('foo', 'bar', 'baz')
#
#  a = foo
#  b = bar
#  c = baz

# Any type can be passed to the function …
# … but in order to print them, the function
# needs to call str()
F_args(   1 ,    2 ,    3 )
#
#  a = 1
#  b = 2
#  c = 3
Github repository about-python, path: /statements/def/arguments.py

Keyword (named) arguments

#!/usr/bin/python3

def F_named_args(a, b, c = 'FOO', d = 'BAR', e = 'BAZ'):
    print(''               )
    print('  a = ' + str(a))
    print('  b = ' + str(b))
    print('  c = ' + str(c))
    print('  d = ' + str(d))
    print('  e = ' + str(e))

# --------------------------
#
#     Normal call
#
F_named_args('one', 'two')
#
#  a = one
#  b = two
#  c = FOO
#  d = BAR
#  e = BAZ

# -------------------------------
#
#     Explicitely pass a value for a
#     key-argument:
#
F_named_args('one', 'two', d='DDD')
#
#  a = one
#  b = two
#  c = FOO
#  d = DDD
#  e = BAZ

# -------------------------------
#
#     Positional arguments can
#     be named, too:
#
F_named_args(b='BBB', a='AAA')
#
#  a = AAA
#  b = BBB
#  c = FOO
#  d = BAR
#  e = BAZ
Github repository about-python, path: /statements/def/keyword-arguments.py

Argument with one star (or asterisk)

An argument that is prefixed with a star (asterisk) (*b) allows to pass any number of positional arguments to the function.
The type of the argument is a tuple, thus, it is possible to iterate over the optional values that are passed to the function.
#!/usr/bin/python3

def one_star(a, *b):
    print('')
    print('  a = ' + str(a))
    print('  type(b) = ' + str(type(b)))
    for b_ in b:
        print('  b_= ' + str(b_))

one_star('foo')
#
#  a = foo
#  type(b) = <class 'tuple'>

one_star('bar', 'baz')
#
#  a = bar
#  type(b) = <class 'tuple'>
#  b_= baz

one_star('one', 'two', 'three')
#
#  a = one
#  type(b) = <class 'tuple'>
#  b_= two
#  b_= three

# one_star(a = 'a', b='b', c='c') # --> TypeError: one_star() got an unexpected keyword argument 'b'
Github repository about-python, path: /statements/def/one-star.py

Argument with two stars

Similarly, an argument can be declared with two prefixing stars. In that case, the function expects there to be passed any number of named arguments. The type of the argument within the function is a dict.
#!/usr/bin/python3

def two_stars(a, **b):
    print('')
    print('  a = ' + str(a))
    print('  type(b) = ' + str(type(b)))

    for k,v in b.items():
        print('  ' + k + ' = ' + str(v))

two_stars('foo')
#
#  a = foo
#  type(b) = <class 'dict'>
#

two_stars('bar', num = 42)
#
#  a = bar
#  type(b) = <class 'dict'>
#  num = 42

two_stars('baz', x = 'eggs', y = 'why')
#
#  a = baz
#  type(b) = <class 'dict'>
#  x = eggs
#  y = why
Github repository about-python, path: /statements/def/two-stars.py
See also merging two dictionaries where two stars are used to »unpack« dictionaries.

Calling a function

When a function is called, a namespace is created.
This namespace is destroyed when the function is exited.
When functions are called recursively, each function invocation gets its own namespace.

docstring

If a function's first statement is just a string literal, the value of this string becomes the function's docstring and can be queried on the function object's __doc__ attribute.
def F():
    'This is the functions docstring'
    return 4


def G(a):
    """\
This docstring demonstrates that
a docstring can also span
multiple lines."""

    return a ** 2

print(F.__doc__)
print(G.__doc__)
Github repository about-python, path: /statements/def/docstring.py

Symbol table

The def statement inserts the function name in the current symbol table.

TODO

In order to create a generator function, the function definition must have a yield statement - and this is also sufficient to create such a generator function.

See also

Function decorators
Nesting functions
statements
The asyncio library for async def.

Index