Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows a simple way of externally controlling which Python functions (out out of some) in your program get executed. The control is done at run time, so no code changes to the program are needed, for different choices. The control is done using a text file.

Python, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Driving Python function execution from a text file.
# Author: Vasudev Ram: 
# https://vasudevram.github.io, 
# http://jugad2.blogspot.com
# Copyright 2016 Vasudev Ram

def square(n): return n * n
def cube(n): return n * square(n)
def fourth(n):  return square(square(n))

# 1) Define the fns dict literally ...
#fns = {'square': square, 'cube': cube, 'fourth': fourth}
# 2a) ... or programmatically with a dict comprehension ...
fns = { fn.func_name : fn for fn in (square, cube, fourth) }
# OR:
# 2b) 
# fns = { fn.__name__ : fn for fn in (square, cube, fourth) }
# The latter approach (2a or 2b) scales better with more functions, 
# and reduces the chance of typos in the function names.

with open('functions.txt') as fil:
    for line in fil:
        print
        line = line[:-1] 
        if line.lower() not in fns:
            print "Skipping invalid function name:", line
            continue
        for item in range(1, 5):
            print 'item: ' + str(item) + ' : ' + line + \
            '(' + str(item) + ') : ' + str(fns[line](item)).rjust(3)

The method use an external text file and a simple dict within the program, that maps function name strings to function objects. The text file contains the names of the functions to be run, one per line.

More explanations and sample output at this URL:

http://jugad2.blogspot.in/2016/06/driving-python-function-execution-from.html