Skip to content

Optional Parameters in Python: How to Effortlessly Use and Fix Them

[

Using Python Optional Arguments When Defining Functions

Defining your own functions is an essential skill for writing clean and effective code. In this tutorial, you’ll explore the techniques you have available for defining Python functions that take optional arguments. When you master Python optional arguments, you’ll be able to define functions that are more powerful and more flexible.

Table of Contents

Creating Functions in Python for Reusing Code

You can think of a function as a mini-program that runs within another program or within another function. The main program calls the mini-program and sends information that the mini-program will need as it runs. When the function completes all of its actions, it may send some data back to the main program that has called it.

The primary purpose of a function is to allow you to reuse the code within it whenever you need it, using different inputs if required.

When you use functions, you are extending your Python vocabulary. This lets you express the solution to your problem in a clearer and more succinct way.

In Python, by convention, you should name a function using lowercase letters with words separated by an underscore, such as do_something(). These conventions are described in PEP 8, which is Python’s style guide. You’ll need to add parentheses after the function name when you call it. Since functions represent actions, it’s a best practice to start your function names with a verb to make your code more readable.

Defining Functions With No Input Parameters

In this tutorial, you’ll use the example of a basic program that creates and maintains a shopping list and prints it out when you’re ready to go to the supermarket.

Start by creating a shopping list:

shopping_list = {
"Bread": 1,
"Milk": 2,
"Chocolate": 1,
"Butter": 1,
"Coffee": 1,
}

Now let’s define a function print_shopping_list that takes no input parameters. This function will print out the contents of the shopping list. Here’s how you define it:

def print_shopping_list():
for item, quantity in shopping_list.items():
print(f"{quantity} {item}")

To call the function and print the shopping list, simply use the following code:

print_shopping_list()

The output will be:

1 Bread
2 Milk
1 Chocolate
1 Butter
1 Coffee

In this example, the function print_shopping_list does not require any input parameters because it has access to the shopping_list variable defined outside of the function. By defining functions that take no input parameters, you can reuse your code to perform specific actions without needing to pass any arguments.

Using Python Optional Arguments With Default Values

Python allows you to define functions with optional arguments, which means that the arguments can be omitted when the function is called. These optional arguments can also have default values assigned to them.

Default Values Assigned to Input Parameters

Let’s modify the print_shopping_list function to include an optional argument called sort_by_quantity. This argument will determine whether the shopping list should be sorted by quantity before printing. By default, the shopping list will not be sorted.

def print_shopping_list(sort_by_quantity=False):
if sort_by_quantity:
sorted_list = sorted(shopping_list.items(), key=lambda x: x[1])
for item, quantity in sorted_list:
print(f"{quantity} {item}")
else:
for item, quantity in shopping_list.items():
print(f"{quantity} {item}")

To call the function and print the shopping list sorted by quantity, use the following code:

print_shopping_list(sort_by_quantity=True)

The output will be:

1 Chocolate
1 Butter
1 Coffee
1 Bread
2 Milk

By adding the sort_by_quantity=False parameter in the function definition, we made it optional. If the argument is omitted when the function is called, it will default to False. This allows the caller to choose whether they want the shopping list sorted by quantity or not.

Common Default Argument Values

In Python, you can use any valid expression as the default value for an argument. The default value is evaluated once when the function is defined, not each time the function is called.

Here are some common use cases of default arguments:

  • Assigning an empty list as a default argument: def func(arg=[]):
  • Assigning a dictionary as a default argument: def func(arg={}):
  • Assigning a unique object as a default argument: def func(arg=sentinel):

Keep in mind that mutable default arguments can lead to unexpected behavior. If you modify the default argument within the function, the modifications will persist across multiple calls to the function. To avoid this, it’s best to use immutable objects as default arguments.

Data Types That Shouldn’t Be Used as Default Arguments

Certain data types, such as mutable objects like lists or dictionaries, should not be used as default arguments. Since the default value is created only once when the function is defined, using a mutable object as a default argument can lead to unexpected results.

For example, consider the following function:

def append_to_list(value, lst=[]):
lst.append(value)
return lst

If you call this function multiple times without providing a value for the lst argument, you might expect it to return a new list with just the given value each time. However, because the default value for lst is created only once, the function will actually append the values to the same list on each call:

print(append_to_list(1)) # Output: [1]
print(append_to_list(2)) # Output: [1, 2]
print(append_to_list(3)) # Output: [1, 2, 3]

To avoid this unexpected behavior, it’s recommended to use None as the default argument and create a new empty list inside the function if the argument is None:

def append_to_list(value, lst=None):
if lst is None:
lst = []
lst.append(value)
return lst

When you define functions with optional arguments, you might encounter error messages related to incorrect usage of the arguments. Here are a few common error messages you might come across:

  • TypeError: print_shopping_list() missing 1 required positional argument: 'sort_by_quantity': This error occurs when you forget to pass a required argument to the function. Make sure you provide all the required arguments when calling the function.
  • TypeError: print_shopping_list() got an unexpected keyword argument 'invalid_argument': This error occurs when you provide an invalid or misspelled keyword argument. Double-check the keyword arguments that you’re passing to the function.
  • TypeError: print_shopping_list() takes 0 positional arguments but 1 was given: This error occurs when you use positional arguments instead of keyword arguments to call a function. Check if you’re using the correct syntax for passing arguments.

Using args and kwargs

In addition to defining functions with optional arguments, Python also allows you to define functions that accept any number of arguments or keyword arguments using *args and **kwargs.

Functions Accepting Any Number of Arguments

To define a function that accepts any number of arguments, use the *args syntax. This allows you to pass a variable number of positional arguments to the function.

Here’s an example:

def print_items(*args):
for item in args:
print(item)

You can call this function with any number of arguments:

print_items("Apple", "Banana", "Orange")

The output will be:

Apple
Banana
Orange

The *args parameter collects all the positional arguments passed to the function and stores them in a tuple. You can then iterate over this tuple to access the individual arguments.

Functions Accepting Any Number of Keyword Arguments

To define a function that accepts any number of keyword arguments, use the **kwargs syntax. This allows you to pass a variable number of keyword arguments to the function.

Here’s an example:

def print_items(**kwargs):
for item, quantity in kwargs.items():
print(f"{quantity} {item}")

You can call this function with any number of keyword arguments:

print_items(Apple=1, Banana=2, Orange=3)

The output will be:

1 Apple
2 Banana
3 Orange

The **kwargs parameter collects all the keyword arguments passed to the function and stores them in a dictionary. You can then iterate over this dictionary to access both the keys and values.

Conclusion

In this tutorial, you learned how to define Python functions with optional arguments. These optional arguments can have default values assigned to them, allowing the caller to omit them when calling the function. You also explored how to use args and kwargs to define functions that accept any number of arguments or keyword arguments.

By mastering Python optional arguments and default values, you can create more flexible functions that are capable of handling different scenarios with minimal code duplication. This allows you to write cleaner and more efficient code.