Python - Dynamically naming variables

218 views Asked by At

I have a function in which variables of 'node1', 'node2', 'node3' are referenced.

I would like to make it so that the second time the function is called, 'node1' become 'node1_a' and on the third time 'node1_b' and so on.

These 'dynamic' variables are referenced only within the function. I have some code below if it helps understanding.

def marriage(husband, wife):
    count += 1
    node1 = pydot.Node(str(husband))
    node3 = pydot.Node('node_a', label='', style = 'invisible', shape = 'circle', width = '.001', height = '.001')
    node2 = pydot.Node(str(wife))
    tree.add_edge(pydot.Edge(node1, node3, style = "dashed"))
    tree.add_edge(pydot.Edge(node3, node2, style = "dashed"))
2

There are 2 answers

0
Endzior On BEST ANSWER
def marriage(husband, wife, method_dict):
    count += 1
    method_dict['node1'][count] = pydot.Node(str(husband))
    method_dict['node3'][count]node3 = pydot.Node('node_a', label='', style = 'invisible', shape = 'circle', width = '.001', height = '.001')
    method_dict['node2'][count]node2 = pydot.Node(str(wife))
    tree.add_edge(pydot.Edge(method_dict['node1'][count], method_dict['node3'][count], style = "dashed"))
    tree.add_edge(pydot.Edge(method_dict['node3'][count], method_dict['node2'][count], style = "dashed"))

where

method_dict = {{}}
0
galaxyan On

I think you can try dict the key is var name and the value is var value. The calltimeindex should be changed every time function called.

keyName = [["node"+str(index)+"_"+ chr(i) for i in range(ord('a'),ord('z'))] for index in range(1,4)]

varDict[keyName[varIndex][callTimeIndex]] = value