zhihao_li
zhihao_li

Reputation: 183

Skip a positional argument when calling a function

I am trying to call a python function defined/created by a different person. That function explicitly requries 3 arguments inputs as

def function_name (argument1 argument2 argument3):

However, inside the function, only the argument1 and argument3 are used with the argument2 completely ignored. If I can not modify this function definition and need to call this function, how should I skip providing the argument2? like

function_name (value1, *, value3)

or

function_name(value1, whatever_fake_value, value3)

I know the latter option is definitely going to work, but can I explicitly show (to minimize future confusion) that a argument has been skipped in this function call.

Upvotes: 0

Views: 930

Answers (4)

DrCord
DrCord

Reputation: 3955

Create a wrapper function that calls the old function you can't change with the arguments you care about being passed through and a default in place of the "dead" argument and a clear concise comment explaining the exact situation for future posterity and so your future self is happy with you.

def new_wrapper_function(arg1, arg2):
    # this function is a wrapper that calls old_function with a default argument in position 2 because it is unused
    old_function(arg1, default_dead_arg, arg2)

You would probably have the wrapper function pass None as the "dead" argument, for example:

def new_wrapper_function(arg1, arg2):
    # this function is a wrapper that calls old_function with a default argument in position 2 because it is unused
    old_function(arg1, None, arg2)

Upvotes: 2

Jack
Jack

Reputation: 658

Pass None as the second argument. No harm no foul.

Since the arguments are all required and no defaults, skipping the second one in any way even by passing named arguments would raise a TypeError exception.

Upvotes: 0

LukasNeugebauer
LukasNeugebauer

Reputation: 1337

Why can't you change the definition? If you absolutely have to use it as is, you can pass None or an empty list.

function_name(arg1,None,arg2)

Upvotes: 0

Chrispresso
Chrispresso

Reputation: 4071

You can make argument2 an optional argument and give it a default value. For instance:

def function_name(arg1, arg3, arg2=None):
    pass

Then you can check if arg2 is valid, otherwise ignore it.

Upvotes: 1

Related Questions