Keyword Arguments Passed by Name
π·οΈ Functions / Parameters and Arguments
π± Context Introduction
When you call a function in Python, you can pass values in two ways: by position (the order you list them) or by name (explicitly specifying which parameter gets which value). Keyword argumentsβalso called named argumentsβlet you tell Python exactly which parameter each value belongs to. This makes your code clearer, more flexible, and less error-prone, especially when a function has many parameters or when some parameters have default values.
βοΈ What Are Keyword Arguments?
A keyword argument is a value you pass to a function by explicitly naming the parameter it belongs to.
- Instead of relying on the order of values, you write parameter_name=value inside the function call.
- The order of keyword arguments does not matterβPython matches them by name, not position.
- Keyword arguments are especially useful when a function has optional parameters or when you want to skip some default parameters.
Example of a simple function call:
- Define a function: def greet(name, greeting):
- Call it with keyword arguments: greet(greeting="Hello", name="Alice")
- Output: Hello, Alice!
Notice that the order of greeting and name in the call is reversed from the function definition. Because we used keyword arguments, Python still matches them correctly.
π οΈ Mixing Positional and Keyword Arguments
You can combine positional arguments (values passed by order) with keyword arguments, but there is one important rule:
- Positional arguments must come first, followed by keyword arguments.
- Once you use a keyword argument, all remaining arguments must also be keyword arguments.
Example of mixed usage:
- Function: def book_ticket(destination, date, passenger_name="Guest"):
- Valid call: book_ticket("Paris", "2025-06-15", passenger_name="John")
- Invalid call: book_ticket(destination="Paris", "2025-06-15") β this will cause an error because a positional argument comes after a keyword argument.
π΅οΈ Why Use Keyword Arguments?
Keyword arguments make your code more readable and maintainable. Here are the main benefits:
- Clarity β Anyone reading the code can immediately see what each value represents without looking up the function definition.
- Flexibility β You can skip optional parameters and only specify the ones you need.
- Order independence β You don't have to remember the exact order of parameters.
- Fewer bugs β Mistakes from mixing up argument order are eliminated.
Example of clarity improvement:
- Without keyword arguments: create_user("jsmith", "[email protected]", True, "admin")
- With keyword arguments: create_user(username="jsmith", email="[email protected]", is_active=True, role="admin")
The second version is much easier to understand at a glance.
π Comparison: Positional vs. Keyword Arguments
| Feature | Positional Arguments | Keyword Arguments |
|---|---|---|
| How values are matched | By position (order) in the call | By parameter name in the call |
| Order matters? | Yes β changing order changes meaning | No β order is irrelevant |
| Readability | Can be unclear with many parameters | Very clear β each value is labeled |
| Flexibility | Must provide all required parameters in order | Can skip optional parameters |
| Error-prone? | Higher risk of mixing up values | Lower risk β names prevent confusion |
| Required for all parameters? | No β can mix with keyword arguments | No β can mix with positional arguments |
π§ͺ Practical Examples for Engineers
Example 1: Configuring a server connection
- Function: def connect(host, port=8080, timeout=30, use_ssl=True):
- Call with keyword arguments: connect(host="192.168.1.10", timeout=60, use_ssl=False)
- Here, port keeps its default value of 8080, and only the parameters we care about are specified.
Example 2: Sending a notification
- Function: def send_alert(message, channel="email", priority="low", retry_count=3):
- Call with keyword arguments: send_alert("Disk usage above 90%", priority="high", channel="slack")
- The retry_count parameter uses its default value of 3, and the order of priority and channel does not matter.
Example 3: Creating a cloud resource
- Function: def create_instance(name, region, instance_type="t2.micro", ami_id=None, tags=None):
- Call with keyword arguments: create_instance(name="web-server-01", region="us-east-1", instance_type="t3.medium", tags={"env": "prod"})
- The ami_id parameter is omitted, so it remains None (or whatever default you set).
β Best Practices for Using Keyword Arguments
- Use keyword arguments for any parameter that has a default value β it makes the call self-documenting.
- Always put positional arguments first, then keyword arguments.
- When a function has more than two or three parameters, consider using keyword arguments for all of them.
- Be consistent within your team or project β if you start using keyword arguments for a particular function, use them everywhere that function is called.
- Avoid using keyword arguments for the very first parameter if it is obvious (like a name or ID), but use them for everything else.
π§ Summary
Keyword arguments passed by name are a powerful feature in Python that gives you control over how values are assigned to function parameters. They improve code readability, reduce errors, and give you flexibility to skip optional parameters. By using keyword arguments, you write code that is easier for others (and your future self) to understand and maintain. Remember the simple rule: positional arguments first, keyword arguments second, and always name your arguments when it makes the code clearer.
Keyword arguments allow engineers to pass values to a function by explicitly naming the parameter they want to assign, instead of relying on position.
π Example 1: Basic keyword argument with one parameter
This example shows how to pass a value by naming the parameter directly.
def greet(name):
print("Hello, " + name)
greet(name="Alice")
π€ Output: Hello, Alice
π Example 2: Multiple keyword arguments in any order
This example demonstrates that keyword arguments can be written in any order, unlike positional arguments.
def describe_pet(animal, name):
print(name + " is a " + animal)
describe_pet(name="Buddy", animal="dog")
π€ Output: Buddy is a dog
π Example 3: Mixing positional and keyword arguments
This example shows how to use positional arguments first, then keyword arguments after.
def create_profile(name, age, city):
print(name + " is " + str(age) + " years old from " + city)
create_profile("Emma", city="London", age=28)
π€ Output: Emma is 28 years old from London
π Example 4: Keyword arguments with default parameter values
This example demonstrates how keyword arguments can override default values set in the function definition.
def order_coffee(size="medium", milk="whole", shots=1):
print("Order: " + size + " coffee with " + milk + " milk, " + str(shots) + " shot(s)")
order_coffee(milk="oat", shots=2)
π€ Output: Order: medium coffee with oat milk, 2 shot(s)
π Example 5: Using keyword arguments for clarity in calculations
This example shows how keyword arguments make code more readable for engineers working with multiple numeric inputs.
def calculate_volume(length, width, height):
volume = length * width * height
print("Volume is " + str(volume) + " cubic units")
calculate_volume(width=4, height=3, length=5)
π€ Output: Volume is 60 cubic units
Comparison Table
| Feature | Positional Arguments | Keyword Arguments |
|---|---|---|
| Order matters | Yes | No |
| Parameter name required | No | Yes |
| Can mix with positional | Yes (positional first) | Yes (keyword after positional) |
| Readability for engineers | Lower with many parameters | Higher with named parameters |
| Override defaults | Not possible directly | Yes, by naming the parameter |
π± Context Introduction
When you call a function in Python, you can pass values in two ways: by position (the order you list them) or by name (explicitly specifying which parameter gets which value). Keyword argumentsβalso called named argumentsβlet you tell Python exactly which parameter each value belongs to. This makes your code clearer, more flexible, and less error-prone, especially when a function has many parameters or when some parameters have default values.
βοΈ What Are Keyword Arguments?
A keyword argument is a value you pass to a function by explicitly naming the parameter it belongs to.
- Instead of relying on the order of values, you write parameter_name=value inside the function call.
- The order of keyword arguments does not matterβPython matches them by name, not position.
- Keyword arguments are especially useful when a function has optional parameters or when you want to skip some default parameters.
Example of a simple function call:
- Define a function: def greet(name, greeting):
- Call it with keyword arguments: greet(greeting="Hello", name="Alice")
- Output: Hello, Alice!
Notice that the order of greeting and name in the call is reversed from the function definition. Because we used keyword arguments, Python still matches them correctly.
π οΈ Mixing Positional and Keyword Arguments
You can combine positional arguments (values passed by order) with keyword arguments, but there is one important rule:
- Positional arguments must come first, followed by keyword arguments.
- Once you use a keyword argument, all remaining arguments must also be keyword arguments.
Example of mixed usage:
- Function: def book_ticket(destination, date, passenger_name="Guest"):
- Valid call: book_ticket("Paris", "2025-06-15", passenger_name="John")
- Invalid call: book_ticket(destination="Paris", "2025-06-15") β this will cause an error because a positional argument comes after a keyword argument.
π΅οΈ Why Use Keyword Arguments?
Keyword arguments make your code more readable and maintainable. Here are the main benefits:
- Clarity β Anyone reading the code can immediately see what each value represents without looking up the function definition.
- Flexibility β You can skip optional parameters and only specify the ones you need.
- Order independence β You don't have to remember the exact order of parameters.
- Fewer bugs β Mistakes from mixing up argument order are eliminated.
Example of clarity improvement:
- Without keyword arguments: create_user("jsmith", "[email protected]", True, "admin")
- With keyword arguments: create_user(username="jsmith", email="[email protected]", is_active=True, role="admin")
The second version is much easier to understand at a glance.
π Comparison: Positional vs. Keyword Arguments
| Feature | Positional Arguments | Keyword Arguments |
|---|---|---|
| How values are matched | By position (order) in the call | By parameter name in the call |
| Order matters? | Yes β changing order changes meaning | No β order is irrelevant |
| Readability | Can be unclear with many parameters | Very clear β each value is labeled |
| Flexibility | Must provide all required parameters in order | Can skip optional parameters |
| Error-prone? | Higher risk of mixing up values | Lower risk β names prevent confusion |
| Required for all parameters? | No β can mix with keyword arguments | No β can mix with positional arguments |
π§ͺ Practical Examples for Engineers
Example 1: Configuring a server connection
- Function: def connect(host, port=8080, timeout=30, use_ssl=True):
- Call with keyword arguments: connect(host="192.168.1.10", timeout=60, use_ssl=False)
- Here, port keeps its default value of 8080, and only the parameters we care about are specified.
Example 2: Sending a notification
- Function: def send_alert(message, channel="email", priority="low", retry_count=3):
- Call with keyword arguments: send_alert("Disk usage above 90%", priority="high", channel="slack")
- The retry_count parameter uses its default value of 3, and the order of priority and channel does not matter.
Example 3: Creating a cloud resource
- Function: def create_instance(name, region, instance_type="t2.micro", ami_id=None, tags=None):
- Call with keyword arguments: create_instance(name="web-server-01", region="us-east-1", instance_type="t3.medium", tags={"env": "prod"})
- The ami_id parameter is omitted, so it remains None (or whatever default you set).
β Best Practices for Using Keyword Arguments
- Use keyword arguments for any parameter that has a default value β it makes the call self-documenting.
- Always put positional arguments first, then keyword arguments.
- When a function has more than two or three parameters, consider using keyword arguments for all of them.
- Be consistent within your team or project β if you start using keyword arguments for a particular function, use them everywhere that function is called.
- Avoid using keyword arguments for the very first parameter if it is obvious (like a name or ID), but use them for everything else.
π§ Summary
Keyword arguments passed by name are a powerful feature in Python that gives you control over how values are assigned to function parameters. They improve code readability, reduce errors, and give you flexibility to skip optional parameters. By using keyword arguments, you write code that is easier for others (and your future self) to understand and maintain. Remember the simple rule: positional arguments first, keyword arguments second, and always name your arguments when it makes the code clearer.
Interactive Views
You are currently in π All-in-One mode. Use the tabs at the top to switch to π Theory Only or π» Code Only views.
Keyword arguments allow engineers to pass values to a function by explicitly naming the parameter they want to assign, instead of relying on position.
π Example 1: Basic keyword argument with one parameter
This example shows how to pass a value by naming the parameter directly.
def greet(name):
print("Hello, " + name)
greet(name="Alice")
π€ Output: Hello, Alice
π Example 2: Multiple keyword arguments in any order
This example demonstrates that keyword arguments can be written in any order, unlike positional arguments.
def describe_pet(animal, name):
print(name + " is a " + animal)
describe_pet(name="Buddy", animal="dog")
π€ Output: Buddy is a dog
π Example 3: Mixing positional and keyword arguments
This example shows how to use positional arguments first, then keyword arguments after.
def create_profile(name, age, city):
print(name + " is " + str(age) + " years old from " + city)
create_profile("Emma", city="London", age=28)
π€ Output: Emma is 28 years old from London
π Example 4: Keyword arguments with default parameter values
This example demonstrates how keyword arguments can override default values set in the function definition.
def order_coffee(size="medium", milk="whole", shots=1):
print("Order: " + size + " coffee with " + milk + " milk, " + str(shots) + " shot(s)")
order_coffee(milk="oat", shots=2)
π€ Output: Order: medium coffee with oat milk, 2 shot(s)
π Example 5: Using keyword arguments for clarity in calculations
This example shows how keyword arguments make code more readable for engineers working with multiple numeric inputs.
def calculate_volume(length, width, height):
volume = length * width * height
print("Volume is " + str(volume) + " cubic units")
calculate_volume(width=4, height=3, length=5)
π€ Output: Volume is 60 cubic units
Comparison Table
| Feature | Positional Arguments | Keyword Arguments |
|---|---|---|
| Order matters | Yes | No |
| Parameter name required | No | Yes |
| Can mix with positional | Yes (positional first) | Yes (keyword after positional) |
| Readability for engineers | Lower with many parameters | Higher with named parameters |
| Override defaults | Not possible directly | Yes, by naming the parameter |