Sobes.tech
Junior

What types of arguments do functions have in Python?

sobes.tech AI

Answer from AI

In Python, the following types of function arguments exist:

  • Positional arguments: Passed to the function in a strictly defined order.
  • Keyword arguments: Passed to the function by parameter name, allowing changing the order and making the call more readable.
  • Variable length arguments: Allow the function to accept an arbitrary number of positional or keyword arguments.
    • *args: Collects all remaining positional arguments into a tuple.
    • **kwargs: Collects all remaining keyword arguments into a dictionary.
  • Positional-only arguments: Specified before the / symbol in the function signature. These arguments can only be passed positionally.
  • Keyword-only arguments: Specified after the * or *args in the function signature. These arguments can only be passed by name.

Example:

def example_function(pos_only, /, pos_or_kw, *, kw_only):
    # pos_only - positional only
    # pos_or_kw - positional or keyword
    # kw_only - keyword only
    print(f"Positional only: {pos_only}")
    print(f"Positional or keyword: {pos_or_kw}")
    print(f"Keyword only: {kw_only}")

# Function calls:
example_function(1, 2, kw_only=3)  # Correct
# example_function(1, pos_or_kw=2, 3) # Incorrect - kw_only cannot be positional
# example_function(pos_only=1, 2, kw_only=3) # Incorrect - pos_only cannot be named
example_function(1, pos_or_kw=2, kw_only=3) # Correct - pos_or_kw as named argument

Example with *args and **kwargs:

def variable_args_function(arg1, *args, **kwargs):
    # arg1 - required positional or named
    # args - tuple of remaining positional arguments
    # kwargs - dictionary of remaining named arguments
    print(f"arg1: {arg1}")
    print(f"args: {args}")
    print(f"kwargs: {kwargs}")

variable_args_function(10, 20, 30, name="Alice", age=30)
# Output:
# arg1: 10
# args: (20, 30)
# kwargs: {'name': 'Alice', 'age': 30}

The order of arguments in the function definition is important: positional only, positional or named, *args, keyword only, **kwargs.