Using Keyword-Only Arguments for Clarity in Python

Table of Contents

As a beginner in programming, I often write Python scripts to automate daily manual tasks. Early on, I struggled with confusing function arguments—especially when they were all similar types. After reading some documentation and making a few mistakes, I discovered keyword-only arguments. This simple feature made my code much clearer and easier to use, so I want to share it with fellow beginners.

What Are Keyword-Only Arguments?

In Python, you can force some function arguments to be specified by name (as keywords) rather than by position. This is done by adding a * in the function definition before those arguments:

def send_email(to, *, subject, body):
    pass

Now, when calling send_email, you must specify subject and body as keywords:

send_email("[email protected]", subject="Hello", body="How are you?")

If you forget to use the keywords, Python will give you an error. This helps prevent mistakes, especially when functions have many arguments or similar types.

Why I Find This Helpful

When I started automating tasks, I often got confused about the order of arguments, especially if they were all strings or numbers. By using keyword-only arguments, my scripts became more readable and less error-prone. It also made it easier for me (and others) to understand what each argument means.

Example from My Daily Script

I discovered the value of keyword-only arguments when working with functions that take several boolean options. Without keywords, calling such functions can be confusing:

def process_file(path, read_only, backup, notify):
    pass

# Hard to read:
process_file("data.txt", True, True, False)

With keyword-only arguments, the call becomes much clearer:

def process_file(path, *, read_only=False, backup=False, notify=False):
    pass

# Easy to read:
process_file("data.txt", read_only=True, backup=True, notify=False)

Final Thoughts

If you’re new to Python, try using keyword-only arguments in your functions. It can help make your code clearer and prevent bugs. Happy coding!