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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758199877, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/built-in-functions/locals(91): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78