I want to create a def function name from concatenating "string" + variable + "string" and call that def function.
I am currently using this condensed version of code for simplicity to similarly accomplish tasks and I want to minimize the hard code contents of the function do_update(a):
ROTATE = '90'
ROT20 = [
[0, 0, 0, 0, 0, 0, 0, 0],
[126, 129, 153, 189, 129, 165, 129, 126],
[126, 255, 231, 195, 255, 219, 255, 126],
[0, 8, 28, 62, 127, 127, 127, 54],
[0, 8, 28, 62, 127, 62, 28, 8],
[62, 28, 62, 127, 127, 28, 62, 28],
[62, 28, 62, 127, 62, 28, 8, 8],
[0, 0, 24, 60, 60, 24, 0, 0],
];
def updatevalues90(a):
b = []
for i in range(8):
for j in range(8):
b[i] += a[j] + i
return b
def do_update(a):
if ROTATE == '90':
ROT = [updatevalues90(char) for char in a]
elif ROTATE == '180':
ROT = [updatevalues180(char) for char in a]
elif ROTATE == '270':
ROT = [updatevalues270(char) for char in a]
do_update(ROT20)
Everything I have tried has resulted in Invalid Syntax or ROT filled with the string name of what I want.
I want to take the function call to updatevalues90(char) and instead of needing it hard coded, I want to change it to:
ROT = ["updatevalues" + ROTATE + "(char)" for char in a]
So that whatever value is in ROTATE will become part of the function call, i.e. function name.
My question is how in Python do I concatenate the strings and a variable name into a useable function name?
I think eval, but I can't get the syntax to work for me. Maybe there is something simpler in Python that works?
1 Answer 1
Store your functions in a dict:
updaters = {
'90': updatevalues90,
'180': updatevalues180,
'270': updatevalues270
}
def do_update(a):
ROT = [updaters[ROTATE](char) for char in a]
# return ROT ?
updatevalues*functions look very similar.eval()and similar approaches.