1

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

  • a for arg1,
  • b for arg2
  • d for arg4
  • (and I'm not using arg3).

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.

azro
  • 53,056
  • 7
  • 34
  • 70
nakb
  • 321
  • 1
  • 3
  • 16

2 Answers2

3

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)
RafalS
  • 5,834
  • 1
  • 20
  • 25
1

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)
Petur Ulev
  • 97
  • 9