Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is a keyword argument in Python

Understanding Keyword Arguments in Python

When you're just starting out in the world of programming, you might feel like you've walked into a conversation where everyone else knows what's going on except you. Don't worry! We've all been there, and today we're going to break down one of those terms you might have heard: "keyword arguments" in Python.

The Basics of Functions and Arguments

Before we dive into keyword arguments, let's talk about functions. In programming, a function is like a mini-program that you can run within your larger program. It's a set of instructions that performs a specific task. To perform its task, a function often needs some information from you, which you pass to it when you call the function. This information is known as arguments or parameters.

Positional Arguments: The Default Way

In Python, when you pass arguments to a function, there's a default way to do it, which is by position. This means that the order in which you pass the arguments matters. Here's a simple example:

def greet(first_name, last_name):
    print(f"Hello, {first_name} {last_name}!")

greet('John', 'Doe')

In this code, greet is a function that takes two arguments: first_name and last_name. When we call greet('John', 'Doe'), 'John' is assigned to first_name because it's the first argument, and 'Doe' is assigned to last_name because it's the second. This is what we call positional arguments.

Enter Keyword Arguments

Now, keyword arguments come into play when you want to specify which argument you're passing to the function, regardless of its position. You do this by naming the argument when you call the function. Here's how you can use keyword arguments with the same greet function:

greet(last_name='Doe', first_name='John')

Notice how we switched the order of the last and first names? That's perfectly fine when using keyword arguments because we've explicitly stated which argument is which.

The Advantages of Using Keyword Arguments

Keyword arguments have a couple of benefits that make them handy:

Clarity: When you're reading code, seeing the names of arguments makes it much clearer what each one represents. This is especially true for functions with many parameters or when the values being passed are not self-explanatory.

Flexibility: You can pass the arguments in any order you want. This flexibility can make your code more readable and maintainable.

Mixing Positional and Keyword Arguments

Python is versatile, allowing you to mix positional and keyword arguments. However, there's a rule: you must pass all positional arguments before any keyword arguments. Here's an example:

def register_user(email, username, password):
    # Imagine some code here that registers a user
    print(f"User {username} registered with email: {email}")

register_user('john.doe@example.com', username='johndoe', password='supersecure')

In the example above, 'john.doe@example.com' is a positional argument, and username='johndoe' and password='supersecure' are keyword arguments.

Default Values and Keyword-Only Arguments

Keyword arguments become even more powerful when combined with default values. You can define a function with default values for some parameters, which will be used if you don't provide them:

def make_coffee(size, coffee_type='espresso'):
    print(f"Making a {size} cup of {coffee_type}")

make_coffee('large')

In this case, coffee_type has a default value of 'espresso', so if you don't specify the coffee type, it will make an espresso by default.

Python also allows you to create keyword-only arguments. These are arguments that can only be specified using keywords and not positionally. This is done after a * in the function definition:

def make_smoothie(*, fruit, liquid='water'):
    print(f"Making a smoothie with {fruit} and {liquid}")

make_smoothie(fruit='banana')

Here, fruit must be passed as a keyword argument, and liquid has a default value of 'water'.

Real-world Analogy

Think of a keyword argument like filling out a form with labeled fields. It doesn't matter in which order you fill in the fields, as long as each piece of information goes into its correct labeled field. On the other hand, positional arguments are like giving someone a list of ingredients to bake a cake in the exact order they need to be added.

Code Examples in Action

Let's look at a more complex example that uses everything we've talked about:

def create_profile(username, email, password='P@ssw0rd', **extra_info):
    print(f"Username: {username}")
    print(f"Email: {email}")
    print(f"Password: {password}")
    for key, value in extra_info.items():
        print(f"{key}: {value}")

create_profile('janedoe', 'jane.doe@example.com', location='USA', age=30)

In the create_profile function, username and email are positional arguments, password has a default value, and **extra_info allows for an arbitrary number of additional keyword arguments. This is known as a "catch-all" for keyword arguments.

Conclusion: Embracing Flexibility and Clarity

As you continue your journey in programming, you'll find that understanding the tools at your disposal, like keyword arguments, can greatly enhance the readability and functionality of your code. Just like how a well-organized toolbox allows a craftsman to work efficiently and effectively, mastering the use of keyword arguments will help you craft better, more intuitive code. So next time you're writing a function, consider the clarity and flexibility that keyword arguments can provide. They might just be the perfect fit for your programming needs. Happy coding!