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.

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Please take your time and answer with text and explantion at first time, a code-only answer does not really help
Yes that does the job. Thanks.
@azro, if the guy says it does the job, then I guess it's enough :)
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.