CodeGym /Courses /Python SELF EN /Advanced Function Parameter Handling

Advanced Function Parameter Handling

Python SELF EN
Level 14 , Lesson 3
Available

7.1 Getting All Function Arguments

Python's got some pretty cool ways to snag all the parameters passed into a function. Let's check 'em out.

Using *args

*args lets you pass a variable number of positional (regular) arguments into a function. These arguments are packed into a tuple and can be handled within the function.


def print_numbers(*args):
    for arg in args:
        print(arg)
        
print_numbers(1, 2, 3, 4, 5)

Explanation

The function print_numbers takes a variable number of positional arguments packed into the tuple args. You can loop through the arguments inside the function using a for loop.

Advantages

  • Flexibility: Lets you pass any number of arguments into the function.
  • Versatility: Handy for functions with an undefined number of parameters.

Using **kwargs

**kwargs lets you pass a variable number of keyword arguments into a function. These arguments are packed into a dictionary and can be handled within the function.


def print_person_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
        
print_person_info(name="Alice", age=30, city="New York")

Explanation

The function print_person_info takes a variable number of keyword arguments packed into the dictionary kwargs. You can loop through the arguments inside the function using the dictionary's items() method.

Advantages

  • Flexibility: Allows passing any number of keyword arguments into the function.
  • Readability: Keyword arguments make function calls more readable.

7.2 Fixing Argument Types

Positional-Only Arguments

In Python 3.8 and above, you can define functions with positional arguments that can only be passed by position using the symbol / in the function definition.


def greet(name, /, greeting="Hello"):
    print(f"{greeting}, {name}!")
        
greet("Alice")  # Output: Hello, Alice!
greet("Alice", greeting="Hi")  # Output: Hi, Alice!
# greet(name="Alice")  # Error: TypeError

Explanation

The function greet accepts the argument name, which can be passed only by position. Arguments before / must be passed by position only.

This approach allows you to restrict how arguments are passed, improving readability and preventing errors.

Keyword-Only Arguments

You can also define function parameters that can only be passed by name using the symbol * in the function definition.


def greet(*, name, greeting="Hello"):
    print(f"{greeting}, {name}!")
        
greet(name="Alice")  # Output: Hello, Alice!
greet(name="Alice", greeting="Hi")  # Output: Hi, Alice!
# greet("Alice")  # Error: TypeError

The function greet accepts the argument name, which can only be passed by name. Arguments after * must be passed by name only.

This approach enforces explicit naming of arguments, improving code readability.

Combining Positional and Keyword Arguments

You can also combine positional and keyword arguments for maximum flexibility.


def greet(name, /, *, greeting="Hello"):
    print(f"{greeting}, {name}!")
        
greet("Alice")  # Output: Hello, Alice!
greet("Alice", greeting="Hi")  # Output: Hi, Alice!
# greet(name="Alice")  # Error: TypeError

The function greet accepts the argument name, which can only be passed by position, and the keyword argument greeting, which must be provided by name. Using both / and * allows the combination of positional and keyword arguments.

Full Example of All Three Situations:


def full_example(a, b, /, c, d, *, e, f):
    print(f"a={a}, b={b}, c={c}, d={d}, e={e}, f={f}")
        
# Calling the function with various arguments
full_example(1, 2, 3, 4, e=5, f=6)  # All arguments passed correctly
# full_example(a=1, b=2, c=3, d=4, e=5, f=6)  # Error: TypeError

Explanation

  • Positional-Only Arguments: a and b must be passed by position only.
  • Regular Positional or Keyword Arguments: c and d can be passed either by position or by name.
  • Keyword-Only Arguments: e and f must be passed by name only.
2
Task
Python SELF EN, level 14, lesson 3
Locked
Infinity is not the limit.
Infinity is not the limit.
2
Task
Python SELF EN, level 14, lesson 3
Locked
Infinite Number of Names.
Infinite Number of Names.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION