Python > Core Python Basics > Functions > Function Arguments (positional, keyword, default)
Understanding Function Arguments in Python
This snippet demonstrates the use of positional, keyword, and default arguments in Python functions. Understanding these argument types is crucial for writing flexible and maintainable code.
Positional Arguments
Positional arguments are arguments that are passed to a function in the order they are defined in the function signature. The first argument passed corresponds to the first parameter, the second argument to the second parameter, and so on. In this example, 'hamster' is assigned to `animal_type` and 'Harry' to `pet_name` based on their position in the function call. The order matters significantly.
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name}.")
describe_pet('hamster', 'Harry')
Keyword Arguments
Keyword arguments allow you to pass arguments to a function by explicitly naming the parameter to which the argument should be assigned. This allows you to pass arguments in any order. Using keyword arguments can make your code more readable, especially when a function has many parameters. The key benefit is improved code clarity and readability. This can be particularly helpful when a function accepts many arguments.
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name}.")
describe_pet(animal_type='hamster', pet_name='Harry')
describe_pet(pet_name='Harry', animal_type='hamster')
Default Arguments
Default arguments specify a default value for a parameter. If a value for that parameter is not provided in the function call, the default value is used. In this example, `animal_type` has a default value of 'dog'. If we call `describe_pet('Willie')`, `animal_type` will default to 'dog'. Default arguments must come after positional arguments in the function definition.
def describe_pet(pet_name, animal_type='dog'):
"""Display information about a pet."""
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name}.")
describe_pet(pet_name='Willie')
describe_pet(pet_name='Harry', animal_type='hamster')
Mixing Argument Types
You can mix positional, keyword, and default arguments in a function definition. Positional arguments must come first, followed by keyword arguments or arguments with default values. When calling the function, you can use positional arguments for the initial parameters and then use keyword arguments for the remaining parameters, especially those with default values. Order matters for positional arguments, while keyword arguments can be passed in any order as long as you specify the parameter name.
def my_function(a, b, c=10, d=20):
print(f"a={a}, b={b}, c={c}, d={d}")
my_function(1, 2)
my_function(1, 2, 3)
my_function(1, 2, c=3, d=4)
my_function(1, 2, d=4)
Concepts Behind the Snippet
The core concepts involve function definition and calling, parameter passing mechanisms, and argument resolution. Understanding the order of arguments and the precedence of keyword arguments over positional ones is crucial. Default values provide flexibility and simplify function calls when certain parameters have commonly used values.
Real-Life Use Case
Consider a configuration function for a database connection. It might have parameters like hostname, port, username, password, and database name. You could provide default values for the hostname and port, so users only need to specify the username, password, and database name if they are using the default server and port.
Best Practices
Always define default values for parameters that have sensible defaults. Use keyword arguments when calling functions with many parameters to improve readability. Avoid using mutable default arguments (like lists or dictionaries) as they can lead to unexpected behavior (see FAQ). Document your functions clearly, explaining the purpose of each parameter and its expected type.
Interview Tip
Be prepared to explain the difference between positional, keyword, and default arguments. Also be prepared to discuss the implications of mutable default arguments. A common interview question involves writing a function that accepts a variable number of arguments (using `*args` and `**kwargs`).
When to Use Them
Use positional arguments when the order of the arguments is clear and well-defined. Use keyword arguments when the order is not obvious, or when you want to provide a value for a specific parameter without providing values for preceding parameters. Use default arguments when a parameter has a commonly used value that you want to provide as a default.
Alternatives
While positional, keyword and default parameters are standard, the `*args` and `**kwargs` constructs exist as ways to pass variable numbers of parameters to a function. These are often used as wrapper functions. They can also be used in combination with the standard parameter types.
FAQ
-
What happens if I provide a positional argument after a keyword argument?
Python will raise a `SyntaxError` because positional arguments must always precede keyword arguments. -
Why should I avoid using mutable default arguments?
Mutable default arguments are created only once when the function is defined. Subsequent calls to the function that modify the default argument will affect future calls. This can lead to unexpected behavior. For example:def append_to_list(value, my_list=[]): my_list.append(value) return my_list print(append_to_list(1)) print(append_to_list(2))
This code will print[1]
and then[1, 2]
, because the same list object is used for both calls. The workaround is:def append_to_list(value, my_list=None): if my_list is None: my_list = [] my_list.append(value) return my_list
-
Can I use a keyword argument for a parameter that doesn't have a default value?
Yes, you can use keyword arguments for any parameter, regardless of whether it has a default value or not.