Python Star(*) and Slash(/) in Args in Methods

created:

updated:

tags: python

Keyword-Only Arguments

I encountered a method definition like the following today:

def starry_method(sky, *, lights=None, glitter=None):
    ...

In this case, lights and glitter are keyword-only arguments, meaning that these arguments will be supplied with keyword only and not as positional arguments.

  • This means that if we use this method as starry_method("skyArg", "lightsArg", "glitterArg"), this will raise an error because lights and glitter were not provided with keywords.

This starry_method() accepts optional lights and glitter arguments. This method also does not allow any positional arguments after the first one, sky.

  • This means that if user does not provide with any argument for lights or glitter, that is fine as they have default value as None.

Advantage

Keyword arguments often help function calls become more readable.

Position-Only Arguments

Similarly, we can also specify position-only arguments.

def starry_method(sky, ground, /, *, lights=None, glitter=None):
    ...

In the above snippet, sky and ground are position-only arguments as they are defined before / symbol. “The / symbol in the argument list indicates where positional-only arguments end”. So, we can call starry_method(1, 2, lights="lightsArg", glitter="glitterArg"). In the contrary, if we specify keyword arguments for sky and ground such as starry_method(sky=1, ground=2, lights="lightsArg", glitter="glitterArg"), then it will raise an error for specifying keywords.

Advantage

Positional-only arguments help function calls become decoupled with argument names. This is especially helpful when function’s argument names change.

Either Positional or Keyword Arguments

Python’s default arguments can be positional or keyword arguments. In case both / and * are used in arguments list in a method, they’re between / and *.

def starry_method(sky, ground, /, moon="moonArg", *, lights=None, glitter=None):
    ...

In this snippet, moon can be either positional or keyword arguments, or it does not need to be provided as it’s optional. We can call this method in a few different ways:

starry_method("skyArg", "groundArg", "moonArg2")  # as positional arg
starry_method("skyArg", "groundArg", moon="moonArg2")  # as keyword arg
starry_method("skyArg", "groundArg")  # as `moon` is an optional arg

References

  • PEP-3102 guide
  • Effective Python: Item 25: Clarity with Keyword-Only and Positional-Only Arguments