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)
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')
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.