In Python’s function parameter lists, a standalone <span>*</span> is a special syntax that indicates the start of mandatory keyword-only arguments.
Detailed Explanation
When you see a standalone <span>*</span> in a function definition, it means: All parameters defined after <span>*</span> must be passed using keyword arguments and cannot be passed as positional arguments.
Example Illustration
For example, consider the provided <span>read_10x_h5</span> function:
def read_10x_h5(
filename: Path | str,
*,
genome: str | None = None,
gex_only: bool = True,
backup_url: str | None = None,
) -> AnnData:
# ... function body ...
The parameters here are divided into two parts by <span>*</span>:
- 1.
<span>*</span>Parameters before it:<span>filename</span>.
- • This parameter can be passed as either a positional or keyword argument.
- • For example:
<span>read_10x_h5("my_data.h5")</span>or<span>read_10x_h5(filename="my_data.h5")</span>.
<span>*</span> Parameters after it: <span>genome</span>, <span>gex_only</span>, <span>backup_url</span>.- • These parameters are mandatory keyword arguments.
- • You cannot call the function like this:
<span>read_10x_h5("my_data.h5", "hg38", False)</span>. This will raise a<span>TypeError</span>because<span>genome</span>and<span>gex_only</span>are placed after<span>*</span>and cannot be passed positionally. - • You must call the function like this:
<span>read_10x_h5("my_data.h5", genome="hg38", gex_only=False)</span>.
Why Use <span>*</span>?
Using mandatory keyword arguments has several significant benefits:
- 1. Improves Code Readability: When a function has many parameters, especially when some are optional or of similar types, using keywords to specify the meaning of parameters makes the code very clear. Readers can immediately understand the purpose of each value without needing to memorize the order of parameters.
- • For example,
<span>read_10x_h5("data.h5", gex_only=False)</span>is much easier to understand than<span>read_10x_h5("data.h5", False)</span>.
<span>*</span> as mandatory keyword arguments means that all old code that does not use the new parameters does not need to be modified. If the new parameters were placed in the middle, it would break the existing positional argument calling style.Conclusion
<span>*</span> in function definitions serves to separate positional parameters from mandatory keyword arguments, forcing the caller to use keyword form for all subsequent parameters, thereby enhancing code clarity, readability, and robustness. This is a very good feature introduced in Python 3, widely used in the API design of many excellent open-source libraries such as <span>pandas</span>, <span>numpy</span>, <span>scikit-learn</span>, and <span>scanpy</span>.