What is asterisk in python class o function argument list


We see asterisk in some python class or function argumentlist, what does it mean?

What are Keyword-Only Arguments?

Introduced in Python 3, keyword-only arguments are function or method arguments that must be specified by their name. They prevent the confusion that can arise from having multiple parameters, enhancing code readability and reducing the likelihood of errors.

Syntax and Usage

The syntax for keyword-only arguments involves placing an asterisk * in the function’s or method’s parameter list. Parameters after the asterisk are treated as keyword-only. Let’s see this in the context of a Python class method:

class DocumentRetriever:
def _get_relevant_documents(self, query: str, *, run_manager):
# Implementation
pass

In the above example, the _get_relevant_documents method of the DocumentRetriever class has two parameters: query and run_manager. The asterisk * before run_manager indicates that it is a keyword-only argument.

Why Use Keyword-Only Arguments?

  • Clarity: Keyword-only arguments require the caller to explicitly specify the name of the parameter, making the code more readable and clear. This is especially beneficial in methods with multiple parameters.

  • Avoiding Errors: They help prevent bugs that might occur when a caller mixes up the order of arguments.

  • Flexibility in API Design: They allow method signatures to be changed more easily, such as adding new parameters without worrying about their position.

Calling Methods with Keyword-Only Arguments

To call a method with keyword-only arguments, you simply need to specify the keyword:

retriever = DocumentRetriever()
retriever._get_relevant_documents("some query", run_manager=some_manager)

In this call, run_manager must be explicitly named. This is particularly useful when the function or method has multiple parameters, reducing the risk of passing arguments in the wrong order.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC