Positional-Only Arguments in Python

Positional-Only Arguments in Python

Positional-only arguments are function parameters that must be passed by position (order) and cannot be passed by keyword name.

Syntax

Use the / symbol in the function definition to indicate that all parameters before it are positional-only:

python

def function_name(param1, param2, /, param3, param4):
    # function body

Simple Examples

Example 1: Basic Positional-Only Arguments

python

def calculate_area(length, width, /):
    area = length * width
    print(f"Area: {area} square units")

# These work (positional arguments):
calculate_area(5, 3)    # Output: Area: 15 square units
calculate_area(10, 2)   # Output: Area: 20 square units

# This will cause an ERROR (keyword arguments not allowed):
# calculate_area(length=5, width=3)

Example 2: Mixing Positional-Only and Regular Arguments

python

def create_person(name, age, /, country):
    print(f"Name: {name}, Age: {age}, Country: {country}")

# Valid calls:
create_person("Alice", 25, "USA")          # Positional for all
create_person("Bob", 30, country="Canada") # Positional for first two, keyword for last

# Invalid calls:
# create_person(name="Charlie", age=35, country="UK")  # ERROR: name and age are positional-only

Example 3: Practical Example – Math Operations

python

def power(base, exponent, /):
    result = base ** exponent
    print(f"{base} to the power of {exponent} = {result}")

power(2, 3)     # Output: 2 to the power of 3 = 8
power(5, 2)     # Output: 5 to the power of 2 = 25

# This would cause an error:
# power(base=2, exponent=3)

Example 4: With Default Arguments

python

def greet(name, /, message="Hello"):
    print(f"{message}, {name}!")

# Valid calls:
greet("John")                   # Output: Hello, John!
greet("Sarah", "Hi")            # Output: Hi, Sarah!
greet("Mike", message="Hey")    # Output: Hey, Mike!

# Invalid call:
# greet(name="Emma")  # ERROR: name is positional-only

Real-World Use Cases

Example 5: File Processing

python

def process_file(file_path, /, mode="read"):
    print(f"Processing {file_path} in {mode} mode")

process_file("data.txt")                # Output: Processing data.txt in read mode
process_file("image.jpg", "write")      # Output: Processing image.jpg in write mode

# This would be invalid:
# process_file(file_path="document.pdf")

Example 6: Coordinate System

python

def plot_point(x, y, /, color="black", size=1):
    print(f"Point at ({x}, {y}) with {color} color and size {size}")

plot_point(10, 20)                      # Output: Point at (10, 20) with black color and size 1
plot_point(5, 15, "red", 2)             # Output: Point at (5, 15) with red color and size 2
plot_point(3, 7, color="blue", size=3)  # Output: Point at (3, 7) with blue color and size 3

# Invalid:
# plot_point(x=1, y=2)

Key Points to Remember

  1. Positional-only arguments must come before theĀ /
  2. They cannot be passed using keyword syntax
  3. They make function APIs more strict and predictable
  4. Useful when parameter names might change in the future
  5. Helps prevent users from relying on specific parameter names

When to Use Positional-Only Arguments

  • When parameter names are not descriptive or might change
  • For mathematical functions where order matters (like coordinates)
  • When you want to enforce a specific calling convention
  • For internal functions where you want to prevent keyword usage

Positional-only arguments give you more control over how your functions are called!

Similar Posts

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

  • positive lookbehind assertion

    A positive lookbehind assertion in Python’s re module is a zero-width assertion that checks if the pattern that precedes it is present, without including that pattern in the overall match. It’s the opposite of a lookahead. It is written as (?<=…). The key constraint for lookbehind assertions in Python is that the pattern inside the…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

  • re.sub()

    Python re.sub() Method Explained The re.sub() method is used for searching and replacing text patterns in strings. It’s one of the most powerful regex methods for text processing. Syntax python re.sub(pattern, repl, string, count=0, flags=0) Example 1: Basic Text Replacement python import re text = “The color of the sky is blue. My favorite color is blue too.” #…

  • Built-in Object & Attribute Functions in python

    1. type() Description: Returns the type of an object. python # 1. Basic types print(type(5)) # <class ‘int’> print(type(3.14)) # <class ‘float’> print(type(“hello”)) # <class ‘str’> print(type(True)) # <class ‘bool’> # 2. Collection types print(type([1, 2, 3])) # <class ‘list’> print(type((1, 2, 3))) # <class ‘tuple’> print(type({1, 2, 3})) # <class ‘set’> print(type({“a”: 1})) # <class…

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

Leave a Reply

Your email address will not be published. Required fields are marked *