Python Asterisk and Slash Special Parameters

petr | 1. června 2024 3:06

You use a bare asterisk to define a boundary between arguments that you can pass by either position or keyword from those that you must pass by keyword. You use the slash to define a boundary between those arguments that you must pass by position from those that you can pass by either position or keyword. Here’s a visual that summarizes how to use these symbols:

Left side Divider Right side
Positional-only arguments / Positional or keyword arguments
Positional or keyword arguments * Keyword-only arguments

 

>>> def asterisk_usage(either, *, keyword_only):
...     print(either, keyword_only)
...
>>> asterisk_usage(either="Frank", keyword_only="Dean")
Frank Dean

>>> asterisk_usage("Frank", keyword_only="Dean")
Frank Dean

>>> asterisk_usage("Frank", "Dean")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: asterisk_usage() takes 1 positional argument but 2 were given

 

>>> def slash_usage(positional_only, /, either):
...     print(positional_only, either)
...
>>> slash_usage("Frank", either="Dean")
Frank Dean

>>> slash_usage(positional_only="Frank", either="Dean")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slash_usage() got some positional-only arguments
passed as keyword arguments: 'positional_only'

>>> slash_usage("Frank", "Dean")
Frank Dean

 

https://realpython.com/python-asterisk-and-slash-special-parameters/

Sidebar

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Magnam doloremque hic consequatur numquam porro quos maiores sit. Recusandae sint eaque maxime provident neque est, consequuntur aspernatur eius veritatis soluta ab.

Know more!