0

I'm using sage to print diffrent graphs with a script written in python. I'm trying to write a generic code that allows me to print all the graphs. For example I have :

g1 = graphs.BarbellGraph(9, 4) 
g2 = graphs.RandomNewmanWattsStrogatz(12, 2, .3)

The graph depends on the number and type of my parameters and I must adapt my code to make it work with diffrent cases.

My code :

registry = {"graphs": graphs, "digraphs":digraphs}
methodtocall = getattr(registry["graphs"], "BarbellGraph")
result = methodtocall(2,3)
print(result)

with this code I get as a result

graphs.BarbellGraph(2, 3) 

my problem is that methodtocall accepts 2 parameters in the code above and I want to change it depending on the number of parameters for the chosen graph. How can I change the code to make it dynamic for the parameters ?

if I have N parameters I want to have

result = methodtocall(param1, ... ,paramN)

thanks in advance

user850287
  • 401
  • 1
  • 6
  • 11
  • Because BarbellGraph is just an example instead of it I retrieve the chosen graph from a list : list_graph[nb_graph]. and for the arguments I have a dictionary where I put the parameters and their values – user850287 Dec 17 '12 at 21:23

2 Answers2

0

I think you are looking for the star-operator (aka "splat" or "unpacking" operator):

result = methodtocall(*[param1, ... ,paramN])
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

If you put the arguments in a list, you can call a function as follows;

graphs.RandomNewmanWattsStrogatz(*parameter_list)

Which will expand the list as position arguments.

If you are writing a function which needs to take position arguments you can accept arbitrary numbers of arguments in a similar manner;

def my_function(*args):
    assert(type(args) == tuple)
Morgan Borman
  • 326
  • 2
  • 4