user3176500
user3176500

Reputation: 389

how to pass a lot of arguments to several functions

it's hard to formulate my question exactly as I can't really make a minimal example, because it's a problem on a large scale. The problem considers code organization:

Let's say I have a script which imports my utility functions and creates a lot of variables

import utility
list_a # list of custom objects
list_b # list of custom objects
list_m # list of numpy matrices
matrix_a
net # networkx object
utility.my_main_func(list_a, list_b, list_m, matrix_a, net)
Then in utility I have
my_main_func(a, b, m, m_a, network)
my_func_one(a, b, m, m_a)   # no network
my_func_two(a, b, m, m_a, network, additional_one)

my_func_three(a, b, m, m_a, network, additional_two)

So my question is what is the idiomatic way to do this, regarding readability and extendibility of the code. Should I use a dictionary and the *args and **kwargs, or is there nothing else to it.

Thanks

Upvotes: 1

Views: 95

Answers (2)

papafe
papafe

Reputation: 3070

Regarding readability, I think there would not be any particular problems with your approach.

Regarding extendibility and usability of the code I think that if your functions are all strictly related, you could make them as method of a class, and have your input values as member variables of the class and initialize them in the constructor.

Upvotes: 0

Tom
Tom

Reputation: 433

You can use *args and **kwargs (one is a sort of array of arguments, the other one is more of a dictionary of arguments, I prefer **kwargs)

def test_args(farg, *args):
    print "Normal argument: ", farg
    for arg in args:
        print "*args argument: ", arg

test_args("normal", "this is args", "another args","another another args")

def test_kwargs(farg, **kwargs):
    print "Normal argument: ", farg
    for key in kwargs:
        print "Keyword - Value: %s: %s" % (key, kwargs[key])

test_kwargs(farg=1, myarg="one", myargtwo="two", myargthree="three")

Upvotes: 1

Related Questions