J.D.
J.D.

Reputation: 169

Defining Python Function with Number of Arguments Controlled by Variable

I know that I can use *args to define a function with an arbitrary number of arguments. My question is a little bit different: What if I want the number of arguments to be controlled by a variable? For example, the number of arguments should be 2n, where the value of n is calculated earlier in the code?

Upvotes: 1

Views: 146

Answers (1)

Matiiss
Matiiss

Reputation: 6156

You can get the number of arguments when using *args with len (because args is a tuple) and act based on that (included some test cases):

number = 2


def func(*args):
    if len(args) != number * 2:
        raise TypeError(f'Expected {number * 2} arguments, got {len(args)}')
    # do some other stuff
    # else clause not needed


# testing
test_cases = [
    (1, 2, 3),
    (1, 2, 3, 4),
    (1, 2, 3, 4, 5)
]

for arguments in test_cases:
    print(f'Calling function with {len(arguments)} arguments')
    try:
        func(*arguments)
    except TypeError as e:
        print(f'Raised an exception: {e}')
    else:
        print('Executed without exceptions')
    print()

# output:
# Calling function with 3 arguments
# Raised an exception: Expected 4 arguments, got 3
# 
# Calling function with 4 arguments
# Executed without exceptions
# 
# Calling function with 5 arguments
# Raised an exception: Expected 4 arguments, got 5

Upvotes: 1

Related Questions