Search notes:

Python functions

Return a tuple

def F():

    return 42, 99, -1


x, y, z = F()

print('x={}, y={}, z={}'.format(x, y, z))
#
# x=42, y=99, z=-1

t = F()
print('type(t) = {}'.format(type(t)))
#
# type(t) = <class 'tuple'>

print('t[0]={}, t[1]={}, t[2]={}'.format(t[0], t[1], t[2]))
#
# t[0]=42, t[1]=99, t[2]=-1

# (a, rest) = F() # -->  ValueError: too many values to unpack (expected 2)
Github repository about-Python, path: /functions/return-tuple.py

Return a function

A function can return another function:
def createMultiplier(t):

    def multiplyBy_t(v):
        return t*v

    return multiplyBy_t


mult_by_4 = createMultiplier(4)
mult_by_9 = createMultiplier(9)

print(mult_by_4(5)) # 20
print(mult_by_9(3)) # 27
Github repository about-Python, path: /functions/return-function.py
See also callable objects.

Global/local variables in a function / symbol tables

When the Python interpreter executes a function, it creates a symbol table for the function for the duration of the execution. This symbol table stores the local variables and the function parameters.
If a value is assigned to a variable in a function, a new local variable is created and stored in the symbol table.
If a variable is referenced in a function, the interpreter first tries to look it up in the current function's symbol table. If it doesn't exist there, it tries to look it up in the symbol table of the enclosing namespace, and so on until it reaches the global symbol table and lastly the symbol table of built in names.
If a value is assigned to variable after referencing it, a UnboundLocalError exception is thrown (local variable … referenced before assignment).
In order to mark a variable in a function as global, the global statement must be used.
The current symbol table is returned by the locals() built-in function, as is demonstrated by the following snippet:
def F(p1, p2):

    var = 'baz'

    sym = locals()
    for k, v in sym.items():
        print('{:3s} = {:20}'.format(k,v))

F('foo', 'bar')
Github repository about-Python, path: /functions/locals.py
This snippet, when executed, prints
p1  = foo
p2  = bar
var = baz
Note also that a def statement inserts the name of the function that is being defined into the (then) current symbol table.

Functions without return statement

A function that is left without explicitly returning a value with the return statement implicitly returns None.
def NoReturnStatement(p):
    print('p = {}'.format(p))

print(NoReturnStatement(42))
Github repository about-Python, path: /functions/no-return.py
This snippet prints
p = 42
None
In this example, the print() function is needed because None is otherwise omitted by the interpreter.

TODO

Function annotations

def func(val: int) -> int:
    return 'this is a string, although return type is indicated as int!'

print(func('this is a string, although value is indicated as int'))

print(func.__annotations__) #  {'val': <class 'int'>, 'return': <class 'int'>}
See also
  • PEP 3107 etc.
  • https://mypy-lang.org/[Mypy] is an optional static type checker for Python that aims to combine the benefits of dynamic (or "duck") typing and static typing.

See also

def
Function decorators
Function parameters
The standard-library functools is used with and for callable objects.

Index