Star and slash in Python's functions definitions

tiLag8080 report abuse

Recently, I start to see stars and slashes in Python's function definitions. They are like regular function's arguments, but nowhere used inside the function. What is their role?

Answers

CabeBe report abuse

It is the new feature implemented in Python 3.8. It allows to mark strictly positional arguments and strictly keyword arguments. For example, given a function:

def example(a, b, /, c, d, *, e, f):
      pass
  • All that stands BEFORE slash - all that arguments (a and b) are only positional. So, when you try to assign values to them using keywords, you will have an error.
  • All arguments that stand AFTER star (e and f) are only keyword arguments. When you try to assign values to them without mentioning their name - you will have an error.
  • Arguments between slash and star (c and d) are normal Python arguments that can be either positional or keyword-assigned.
tiLag8080 report abuse

Thanks, @CabeBe . But what is the profit in making arguments strictly positional? Won't this reduce the code readability?

CabeBe report abuse

You are right. In most cases, it is redundant to have only positional arguments. But there are some cases where positional-only arguments can be useful. For example, when the arguments are hard to give a good descriptive name, but they have the natural ordering (first, second, third, and so on).

Kan13 report abuse

They also can be useful when refactoring. When you need to rename the argument, you can just change the name in the function definition without worrying about changing the name of the parameter in every place of the code where the function is used.

Add Answer

Need support?

Just drop us an email to ... Show more