In this lesson, you will learn how to lock down your function interfaces by enforcing specific arguments to be positional-only using the forward slash (/) symbol.
Why Force Positional Arguments?
Usually, Python is very flexible: you can call a function using positional arguments (like func(10, 20)) or keyword arguments (like func(a=10, b=20)). However, sometimes you want to hide the parameter names from the person using your function. This is useful if you think you might want to rename those parameters later without breaking the code of anyone using your function.
The Forward Slash (/)
You can force arguments to be positional-only by placing a forward slash (/) in your function definition. Every argument placed before that slash must be passed by position; you cannot use the name=value syntax for them.
Take a look at this example:
def calculate_area(length, width, /):
return length * width
# This works perfectly:
print(calculate_area(5, 10))
# This will cause a TypeError:
# print(calculate_area(length=5, width=10))
In the example above, the / tells Python, "Only look at the order of the values, do not look for the names length or width." If you try to use the keyword syntax, Python will raise an error because the function interface strictly forbids it.
Mixing Constraints
You can even mix positional-only, regular, and keyword-only arguments (using the * symbol) in one function. Here is the order:
- Positional-only (before the
/) - Regular arguments (no slash or asterisk attached)
- Keyword-only (after the
*)
Example:
def example(pos_only, /, standard, *, kw_only):
print(pos_only, standard, kw_only)
# Valid call:
example(1, 2, kw_only=3)
By using the forward slash, you gain complete control over how your function is called, ensuring that users interact with your logic exactly the way you intended.
Key Takeaway: Placing a forward slash / in a function signature forces all parameters appearing before it to be passed only by position, preventing the use of keyword arguments for those specific inputs.