Python Keyword-only arguments
1 min read

Python Keyword-only arguments

Python Keyword-only arguments
Photo by Brett Jordan / Unsplash

PEP 3102 introduced keyword-only arguments which enforce specific function arguments to be supplied by a keyword.

By placing an asterisk * as the first function argument, we're telling python that all of the following arguments are required to use their keyword when calling the function.

The keyword arguments can also be passed in any order when using the function.

def calculate_tax(*, before_tax_price, sales_tax_percent, discount_in_dollars):
    """Calculate sales tax after removing discount"""
    discounted_price = before_tax_price - discount_in_dollars
    return (sales_tax_percent / 100) * discounted_price 


calculate_tax(before_tax_price=200, sales_tax_percent=6.5, discount_in_dollars=15)
>>> 12.025

// different order
calculate_tax(before_tax_price=200, discount_in_dollars=15, sales_tax_percent=6.5)
>>> 12.025

If we don't pass in the keywords to the function when using it we get a TypeError error saying the function takes 0 positional arguments.

calculate_tax(before_tax_price=200, sales_tax_percent=6.5, 15)

TypeError: calculate_tax() takes 0 positional arguments but 3 were given

When using this keyword-only argument syntax, we can be sure that anyone that uses this function must always use the arguments by their name which enforces a little safety. If we didn't use the keyword-only argument syntax, we could accidentally pass in parameters in the wrong order to the function which could lead to a bug.

def calculate_tax(before_tax_price, sales_tax_percent, discount_in_dollars):
    """Calculate sales tax after removing discount"""
    discounted_price = before_tax_price - discount_in_dollars
    return (sales_tax_percent / 100) * discounted_price


calculate_tax(200, 6.5, 15)
>>> 12.025 // correct


calculate_tax(200, 15, 6.5) // passing the arguments in the wrong order
>>> 29.025 // incorrect