Adventures in Machine Learning

Mastering Python Function Arguments: Positional vs Keyword-only Arguments

Keyword vs. Positional Arguments in Python: Understanding Syntax Errors

As a Python developer, you’ve probably encountered a syntax error before.

These are pesky error messages that pop up when your code violates the syntax rules of the Python language. One common cause of syntax errors is a mix-up between positional and keyword arguments, which are essential in Python function calls.

In this article, we will explore the distinctions between positional and keyword arguments, what syntax errors are, and how to fix them. Positional arguments and keyword arguments are two types of parameters that can be passed to Python functions.

Positional arguments are defined by their order, while keyword arguments are given an explicit name. Here is an example of a function call with both positional and keyword arguments:

def my_func(a, b, c):
    print(f"a={a}, b={b}, c={c}")  
my_func(1, 2, c=3)         
# a=1, b=2, c=3   

In this example, 1 and 2 are positional arguments because they are passed to the function in the exact order the parameters are defined in the function’s signature.

The argument “c” is a keyword argument because it is provided with a name that matches the corresponding parameter name in the function’s signature.

Syntax Error: Positional Argument Follows Keyword Argument

One of the most common mistakes with keyword and positional arguments in Python is passing positional arguments after keyword arguments.

When you mix up the order, you will receive a syntax error that reads: “SyntaxError: positional argument follows keyword argument.” Here is an example:

my_func(a=1, 2, c=3)     # SyntaxError: positional argument follows keyword argument

This happens because the Python interpreter cannot figure out the correct parameter to assign the value to, whether “2” should be assigned to “a” or “b”. To fix this error, you can pass all arguments as positional arguments or make sure that all keyword arguments come before positional arguments.

Passing All Arguments as Positional or Keyword Arguments

There are multiple ways to pass arguments to a function, which includes using either positional or keyword arguments. While positional arguments are assigned according to the argument’s order, keyword arguments are assigned based on the keyword arguments’ name.

Here’s an example:

my_func(1, c=3, b=2)    # a=1, b=2, c=3  

In this example, we passed all arguments either as positional or keyword arguments. It’s crucial to note that while keyword arguments don’t care about the order they are given, positional arguments do.

When using positional arguments, their order must match the order in which the parameters are defined in the function’s signature. On the other hand, using keyword arguments allows you to pass the arguments in any order, as long as the keyword name is provided.

Positional-Only and Keyword-Only Arguments

Python 3.8 introduced support for two new types of function arguments – positional-only arguments and keyword-only arguments. These can help you design more comprehensive and versatile functions, especially if you are creating an API for other developers to use.

Using Positional-Only Arguments

Positional-only arguments were introduced with the “/” syntax. When a parameter is marked with the “/”, it means that only positional arguments can be used to pass that parameter, and it can’t be passed as a keyword argument.

Here’s an example of a function with positional-only arguments:

def func(a, b, /, c):
    print(a, b, c)
func(1, 2, 3)      # 1 2 3

In this example, the parameter “c” is marked with “/”, which means it is a positional-only argument. This syntax tells the Python interpreter that the “c” parameter should only be passed as a positional argument and not as a keyword argument.

Attempting to pass “c” as a keyword argument would result in a TypeError.

Using Keyword-Only Arguments

Keyword-only arguments were introduced with the “*” syntax. When a parameter is marked with “*”, it means that only keyword arguments can be used to pass that parameter, and it can’t be passed as a positional argument.

Here’s an example of a function with keyword-only arguments:

def func(a, *, b, c):
    print(a, b, c)
func(1, b=2, c=3)      # 1 2 3

In this example, the parameters “b” and “c” are marked with “*”, which means they are keyword-only arguments. This syntax tells the Python interpreter that the “b” and “c” parameters should only be passed as keyword arguments and not as positional arguments.

Attempting to pass “b” or “c” as a positional argument would result in a TypeError. Combining

Positional-Only and Keyword-Only Arguments

You can also combine positional-only arguments, keyword-only arguments, and standard arguments in the same function.

Here’s an example of a function that combines all three types:

def func(a, b, /, *, c, d):
    print(a, b, c, d)
func(1, 2, c=3, d=4)    # 1 2 3 4

In this example, the first two parameters, “a” and “b”, are standard arguments that can be passed as positional or keyword arguments. The third parameter, “c”, is marked as a keyword-only argument and must be passed as a keyword argument.

The fourth parameter, “d”, is also marked as a keyword-only argument and must be passed as a keyword argument. The slash “/” indicates that all parameters before it must be passed as positional arguments.

Conclusion

Understanding positional and keyword arguments, and when to use them, is crucial for writing clear and concise Python code. While syntax errors can be frustrating, the Python interpreter provides helpful messages to guide you in resolving them.

By making use of positional-only and keyword-only arguments, you can create more flexible and robust functions and APIs that can help other developers build on your work.

Rule of Thumb for Using Positional and Keyword Arguments in Python

In Python, positional and keyword arguments are used to pass values to a function. Positional arguments are passed in the order they appear in a function’s signature, while keyword arguments use explicit names that match the function’s parameters.

Both types of arguments are critical in Python, and knowing when to use them can make your code more readable and improve its functionality. In this article, we will discuss the rule of thumb for using positional and keyword arguments in Python, specifically focusing on when to use positional arguments and keyword-only arguments.

When to Use Positional Arguments

In general, you should use positional arguments when the order of the parameters is vital and the parameter names are not critical or may lead to confusion. For example, consider the print() function.

The order of arguments is essential, and the parameter names are not critical for the function’s behavior. Typically, you would call the print() function using positional arguments:

print("Hello", "world")

In this example, “Hello” is the first positional argument, and “world” is the second positional argument.

The order of these arguments matters, as it affects their position in the output. Positional arguments can also be useful when calling a function multiple times using different arguments that have the same parameter name, where maintaining order isn’t critical.

When to Use Keyword-Only Arguments

Keyword-only arguments are used when the argument’s name is critical for the function’s behavior, and the argument’s order could lead to confusion. These types of arguments are defined using the `*` syntax.

In some scenarios, certain arguments are not intended to be included in a particular function’s signature, as it doesn’t make sense from a functional standpoint.

For example, suppose you are implementing a function that calculates the discount rate for a product.

Within the function, you have a fixed discount value and a percentage discount that may change over time. You want to allow users to set the percentage discount, but you don’t want to allow any unnecessary changes to your fixed discount value.

You can use keyword-only arguments to prevent users from altering the fixed discount value:

def calculate_discount(fixed_discount, *, percentage_discount=0.2):
    total_discount = fixed_discount + (fixed_discount * percentage_discount)
    return total_discount

In this example, the parameter fixed_discount is a positional argument, while percentage_discount is a keyword-only argument, as it’s marked with “*”. Positional arguments shouldn’t be used for the percentage_discount as it might confuse users over which parameter value they are entering.

Here, the calculate_discount() function is designed to use the fixed_discount and the percentage discount parameter that users set by entering a keyword.

Combining Positional and Keyword-Only Arguments

When combining positional and keyword-only arguments, it’s essential to maintain a balance between the two types, depending on the context of the program.

In some instances, it makes sense to have all arguments as keyword-only arguments.

Consider a function that takes product orders for a retail website. Within the function, you have fixed arguments such as website login credentials, a list of products, and other customizations that the user is welcomed to input.

It’s advisable to implement keyword-only arguments for the user customizations, further emphasizing the significance of the arguments’ names. Here’s an example:

def process_order(credentials, products, *, customization1, customization2, customization3):
    # Function Logic

In this example, the credentials and products are positional arguments, while the customizations are keyword-only arguments, defined with the character sequence `*`.

The customizations are critical for the function’s behavior, and it makes sense to require the user to input the arguments explicitly by name.

Conclusion

In conclusion, understanding when to use positional and keyword-only arguments can improve the functionality and readability of your Python code. It’s good practice to use positional arguments when the order of the arguments is significant, and arguments names are of little or no importance.

On the other hand, keyword-only arguments are ideal when the argument’s name is critical, and the argument order may lead to confusion. The ability to combine positional and keyword-only arguments is a valuable skill that requires a balance between these two types of arguments.

By adhering to these rules of thumb, you can write more robust and maintainable Python code.

About the Author

Welsh Okallo is a seasoned software engineer with an interest in data analysis and computer vision. He has contributed to several open-source projects on GitHub and enjoys sharing his knowledge with the coding community.

You can follow him on Twitter at @welshokallo. In summary, correct usage of positional and keyword-only arguments can improve the functionality and readability of Python code.

Positional-only arguments are recommended when the order of the parameters is crucial, while keyword-only arguments are useful when the argument’s name plays a significant role in function behavior. Balancing the two types of attributes can be essential in some cases.

For experts in writing Python code, taking advantage of these distinctions can make your code more robust and less susceptible to errors. Remember, adhering to these rules of thumb can make for more maintainable code that is less prone to errors.

Popular Posts