1

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?

3
  • what should happen if more or less than that number of arguments are used? also if using *args, then args is a list, so you can use len(args) (inside the function obvs) and raise a TypeError if the length doesn't match some predetermined value Commented Nov 8, 2021 at 6:17
  • The best way would be to add assert len(args) == 2*n to the first line of the function. Commented Nov 8, 2021 at 6:23
  • Python is a dynamic language, so you can't really raise a compile-time error when the argument count is wrong. The best you can do is the assert method mentioned by @KotaMori Commented Nov 8, 2021 at 6:25

1 Answer 1

1

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

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.