Search notes:

Python: locals()

locals() returns a dict that represents the current symbol table

Simple demonstration

def F():

    if 'x' in locals():
       print('locals() contains x')
    else:
       print('locals() does not contain x')

    x = 42

    if 'x' in locals():
       print('locals() contains x')
    else:
       print('locals() does not contain x')

F()
Github repository about-Python, path: /builtin-functions/locals/demo.py
This script, when executed, prints
locals() does not contain x
locals() contains x

Call functions by name

def F1(a, b):
    print('{} + {} = {}'.format(a, b, a+b))

def F2(a, b):
    print('{} - {} = {}'.format(a, b, a-b))

def F3(a, b):
    print('{} * {} = {}'.format(a, b, a*b))

def F4(a, b):
    print('{} / {} = {}'.format(a, b, a/b))


for nr in range(1, 5):
    locals()['F' + str(nr)](42, 6)
#
#  42 + 6 = 48
#  42 - 6 = 36
#  42 * 6 = 252
#  42 / 6 = 7.0
Github repository about-Python, path: /builtin-functions/locals/call-function-by-name.py

See also

globals()
Python: Built in functions

Index