Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What does the slash(/) in the parameter list of a function mean in Python?
The slash (/) in a function's parameter list marks the boundary between positional-only parameters and other parameters. Parameters before the slash can only be passed by position, not as keyword arguments.
Basic Function Example
Let's first understand a regular Python function with parameters ?
# Creating a Function
def demo(car_name):
print("Car:", car_name)
# Function calls
demo("BMW")
demo("Tesla")
Car: BMW Car: Tesla
Positional-Only Parameters with Slash
The slash (/) denotes that parameters before it are positional-only. Arguments are mapped to parameters based solely on their position.
Example with Custom Function
def calculate(x, y, /):
return x + y
# Valid calls - positional arguments
result1 = calculate(10, 5)
result2 = calculate(20, 15)
print("Result 1:", result1)
print("Result 2:", result2)
Result 1: 15 Result 2: 35
The divmod() Function
The built-in divmod() function is a perfect example of positional-only parameters ?
# Check divmod documentation help(divmod)
Help on built-in function divmod in module builtins:
divmod(x, y, /)
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
Using divmod() with Positional Arguments
# Valid usage - positional arguments
quotient_remainder = divmod(17, 5)
print("17 divided by 5:", quotient_remainder)
# Another example
result = divmod(20, 3)
print("20 divided by 3:", result)
17 divided by 5: (3, 2) 20 divided by 3: (6, 2)
What Happens with Keyword Arguments?
Since parameters before the slash are positional-only, using keyword arguments will raise a TypeError ?
# This will raise an error
try:
divmod(x=10, y=3)
except TypeError as e:
print("Error:", e)
Error: divmod() takes no keyword arguments
Function Parameter Types
| Syntax | Parameter Type | Example |
|---|---|---|
def func(a, /) |
Positional-only |
func(1) ?, func(a=1) ? |
def func(a, b) |
Positional or keyword |
func(1, 2) ?, func(a=1, b=2) ? |
def func(*, a) |
Keyword-only |
func(1) ?, func(a=1) ? |
Conclusion
The slash (/) enforces positional-only parameters, preventing keyword argument usage. This design choice improves function call performance and maintains cleaner APIs for certain built-in functions like divmod().
