nakb
nakb

Reputation: 341

Passing arguments to Python function as a data structure

I am using a 3rd party library function which has a large number of positional and named arguments. The function is called from numerous points in my code with identical arguments/values.

For ease of maintenance I don't want to hard-code the dozens of identical arguments multiple times throughout my code. I was hoping there was a way of storing them once in a data structure so I just need to pass the data structure. Along the lines of the following:

Assume the signature of the function I'm calling looks like:

def lib_function(arg1, arg2, arg3=None, arg4=None): 

Assume that throughout my code I want to call it with values of

I've tried defining a data structure as follows:

arguments = ('a', 'b', {'arg4':'d'})

and using it like this:

res = lib_function(arguments)

but this is obviously not correct - the tuple and dict are not unpacked during the call but are handled as a single first argument.

Is there a way of doing this in Python?

The obvious alternative is to proxy lib_function in my code, with the arguments hard-coded in the proxy which is then called with no arguments. Something like:

def proxy_lib_function():
    return lib_function('a', 'b', arg4='d')

res = proxy_lib_function()

However I wanted to check there isn't a more Pythonic way of doing this.

Upvotes: 1

Views: 2555

Answers (2)

RafalS
RafalS

Reputation: 6324

Separate positional and named arguments and use asterisk unpacking:

def lib_function(arg1, arg2, arg3=None, arg4=None):
    print(locals())


args = ("a", "b")
kwargs = {"arg4": "d"}
res = lib_function(*args, **kwargs)

Upvotes: 3

Petur Ulev
Petur Ulev

Reputation: 97

Your function is:

 def lib_function(arg1, arg2, arg3=None, arg4=None): 

Define another function:

 def yourFunction(x):
    return lib_function(x[0], x[1], x[2], x[3])

The "data structure" would be:

data = [yourData1, yourData2, yourData3, yourData4]

Then you can call your new function with this:

yourFunction(data)

Upvotes: 1

Related Questions