Keyword-Only Arguments in Python and mixed

Keyword-Only Arguments in Python

Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments.

Syntax

Use the * symbol in the function definition to indicate that all parameters after it are keyword-only:

python

def function_name(param1, param2, *, keyword_only1, keyword_only2):
    # function body

Simple Examples

Example 1: Basic Keyword-Only Arguments

python

def create_profile(name, age, *, email, country):
    print(f"Name: {name}, Age: {age}")
    print(f"Email: {email}, Country: {country}")
    print("-" * 30)

# Valid call (must use keywords for email and country):
create_profile("Alice", 25, email="alice@email.com", country="USA")

# Invalid calls:
# create_profile("Bob", 30, "bob@email.com", "UK")  # ERROR: must use keywords
# create_profile("Charlie", 35, "charlie@email.com")  # ERROR

Example 2: With Default Values

python

def order_product(product, quantity, *, discount_code=None, gift_wrap=False):
    print(f"Order: {quantity} x {product}")
    if discount_code:
        print(f"Discount: {discount_code}")
    if gift_wrap:
        print("Gift wrap: Yes")
    print("-" * 25)

# Valid calls:
order_product("Book", 2, discount_code="SAVE10")
order_product("Pen", 5, gift_wrap=True)
order_product("Notebook", 1, discount_code="WELCOME", gift_wrap=True)
order_product("Pencil", 10)  # Uses default values for keyword-only args

Example 3: Only Keyword-Only Arguments

python

def send_message(*, to, subject, body, cc=None):
    print(f"To: {to}")
    print(f"Subject: {subject}")
    print(f"Body: {body}")
    if cc:
        print(f"CC: {cc}")
    print("Message sent!")
    print("-" * 20)

# Must use keywords for all parameters:
send_message(to="friend@email.com", subject="Hello", body="How are you?")
send_message(to="boss@work.com", subject="Report", body="Attached report", cc="team@work.com")

Practical Examples

Example 4: User Registration

python

def register_user(username, password, *, email, phone=None, newsletter=False):
    print(f"Username: {username}")
    print(f"Password: {'*' * len(password)}")
    print(f"Email: {email}")
    if phone:
        print(f"Phone: {phone}")
    print(f"Newsletter: {'Yes' if newsletter else 'No'}")
    print("Registration complete!")
    print("-" * 35)

register_user("john_doe", "secret123", email="john@email.com")
register_user("sarah", "mypass", email="sarah@mail.com", phone="123-4567", newsletter=True)

Example 5: File Operations

python

def open_file(filename, *, mode="read", encoding="utf-8", create_if_missing=False):
    print(f"Opening: {filename}")
    print(f"Mode: {mode}")
    print(f"Encoding: {encoding}")
    print(f"Create if missing: {create_if_missing}")
    print("File ready!")
    print("-" * 20)

open_file("data.txt", mode="write", encoding="ascii")
open_file("notes.txt", create_if_missing=True)
open_file("config.ini", mode="append", encoding="utf-8")

Example 6: Math Calculations

python

def calculate(operation, *, precision=2, show_steps=False):
    if operation == "add":
        result = 5 + 3
    elif operation == "multiply":
        result = 4 * 6
    
    final_result = round(result, precision)
    print(f"Result: {final_result}")
    
    if show_steps:
        print(f"Calculation steps shown for {operation}")

calculate("add", precision=3, show_steps=True)
calculate("multiply", show_steps=False)

Using * Alone for Keyword-Only

Example 7: Empty * for All Keyword-Only

python

def configure_settings(*, theme="light", font_size=12, language="en"):
    print(f"Theme: {theme}")
    print(f"Font size: {font_size}")
    print(f"Language: {language}")
    print("Settings configured!")
    print("-" * 20)

# All arguments must be keyword-only:
configure_settings(theme="dark", font_size=14)
configure_settings(language="es", theme="light")

Mixed with Positional Arguments

Example 8: Positional + Keyword-Only

python

def create_post(title, content, *, author, tags=None, published=True):
    print(f"Title: {title}")
    print(f"Content: {content[:30]}...")  # Show first 30 characters
    print(f"Author: {author}")
    if tags:
        print(f"Tags: {tags}")
    print(f"Published: {published}")
    print("-" * 25)

create_post("Python Tips", "Learn Python programming with these tips...", 
            author="John", tags=["python", "coding"])
create_post("Hello World", "My first blog post...", 
            author="Sarah", published=False)

Key Benefits

  1. Clarity: Makes function calls more readable
  2. Flexibility: Parameters can be specified in any order
  3. Safety: Prevents accidental misuse of parameters
  4. Maintainability: Easier to add new parameters later

When to Use Keyword-Only Arguments

  • When you have many optional parameters
  • When parameter names make the code more readable
  • When you want to enforce explicit naming for certain parameters
  • For configuration settings or options

Remember These Rules

  1. Keyword-only arguments come after *
  2. They must be passed using their keyword names
  3. They can have default values
  4. They make function calls more explicit and readable

Keyword-only arguments help create cleaner, more maintainable code!

Positional-Only & Keyword-Only Mixed Arguments

You can combine positional-only, regular, and keyword-only arguments in a single function using both / and * symbols.

Syntax

python

def function_name(pos_only1, pos_only2, /, regular, *, keyword_only1, keyword_only2):
    # function body

Simple Examples

Example 1: Basic Mixed Arguments

python

def process_data(name, age, /, country, *, email, phone):
    print(f"Name: {name}, Age: {age}")
    print(f"Country: {country}")
    print(f"Email: {email}, Phone: {phone}")
    print("-" * 30)

# Valid call:
process_data("Alice", 25, "USA", email="alice@email.com", phone="123-4567")

# Invalid calls:
# process_data("Alice", 25, "USA", "alice@email.com", "123-4567")  # ERROR: keyword-only args must use keywords
# process_data(name="Bob", age=30, country="UK", email="bob@email.com", phone="987-6543")  # ERROR: name/age are positional-only

Example 2: Math Function with Mixed Arguments

python

def calculate(x, y, /, operation="add", *, precision=2):
    if operation == "add":
        result = x + y
    elif operation == "multiply":
        result = x * y
    else:
        result = x - y
    
    print(f"Result: {round(result, precision)}")

calculate(5, 3)                              # Output: Result: 8
calculate(5, 3, "multiply")                  # Output: Result: 15
calculate(10, 4, operation="subtract")       # Output: Result: 6
calculate(7, 3, precision=4)                 # Output: Result: 10.0
calculate(2.5, 1.3, "multiply", precision=3) # Output: Result: 3.25

Example 3: User Registration

python

def register_user(username, password, /, country="Unknown", *, email, newsletter=False):
    print(f"Username: {username}")
    print(f"Password: {'*' * len(password)}")
    print(f"Country: {country}")
    print(f"Email: {email}")
    print(f"Newsletter: {newsletter}")
    print("Registration successful!")
    print("-" * 40)

register_user("john_doe", "secret123", "USA", email="john@email.com")
register_user("sarah", "mypass", email="sarah@mail.com", newsletter=True)
register_user("mike", "pass123", country="Canada", email="mike@test.com")

Example 4: File Operations

python

def handle_file(filename, /, mode="read", *, encoding="utf-8", buffer_size=1024):
    print(f"File: {filename}")
    print(f"Mode: {mode}")
    print(f"Encoding: {encoding}")
    print(f"Buffer Size: {buffer_size} bytes")
    print("File operation ready!")
    print("-" * 25)

handle_file("data.txt")
handle_file("image.jpg", "write", encoding="binary", buffer_size=2048)
handle_file("document.pdf", mode="append", buffer_size=512)

Visual Breakdown

python

def example(a, b, /, c, d, *, e, f):
    # a, b → Positional-only (must come first, no keywords)
    # c, d → Regular (can be positional or keyword)
    # e, f → Keyword-only (must use keywords)
    pass

More Practical Examples

Example 5: Shopping Cart

python

def add_to_cart(product_id, quantity, /, *, discount_code=None, gift_wrap=False):
    print(f"Adding product #{product_id}, Quantity: {quantity}")
    if discount_code:
        print(f"Discount applied: {discount_code}")
    if gift_wrap:
        print("Gift wrapping selected")
    print("Item added to cart!")
    print("-" * 30)

add_to_cart(101, 2)
add_to_cart(205, 1, discount_code="SUMMER20")
add_to_cart(150, 3, gift_wrap=True)
add_to_cart(300, 5, discount_code="WELCOME10", gift_wrap=True)

Example 6: Drawing Shapes

python

def draw_shape(x, y, /, shape="circle", *, color="black", filled=True, size=1):
    print(f"Drawing {shape} at position ({x}, {y})")
    print(f"Color: {color}, Filled: {filled}, Size: {size}")
    print("Shape drawn!")
    print("-" * 25)

draw_shape(10, 20)
draw_shape(50, 30, "square", color="blue")
draw_shape(100, 40, "triangle", filled=False, size=2)
draw_shape(75, 60, shape="rectangle", color="red", size=1.5)

Key Rules to Remember

  1. Positional-only arguments come before /
  2. Regular arguments come between / and *
  3. Keyword-only arguments come after *
  4. Order must be: Positional-only → Regular → Keyword-only
  5. Default values can be used with any type of argument

Benefits of Mixed Arguments

  • Flexibility: Different calling styles for different parameters
  • Clarity: Makes important parameters stand out
  • Safety: Prevents misuse of certain parameters
  • Maintainability: Easier to extend functions without breaking existing code

This mixed approach gives you maximum control over how your functions are called!

Similar Posts

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

  • Combined Character Classes

    Combined Character Classes Explained with Examples 1. [a-zA-Z0-9_] – Word characters (same as \w) Description: Matches any letter (lowercase or uppercase), any digit, or underscore Example 1: Extract all word characters from text python import re text = “User_name123! Email: test@example.com” result = re.findall(r'[a-zA-Z0-9_]’, text) print(result) # [‘U’, ‘s’, ‘e’, ‘r’, ‘_’, ‘n’, ‘a’, ‘m’, ‘e’, ‘1’, ‘2’,…

  • Dictionaries

    Python Dictionaries: Explanation with Examples A dictionary in Python is an unordered collection of items that stores data in key-value pairs. Dictionaries are: Creating a Dictionary python # Empty dictionary my_dict = {} # Dictionary with initial values student = { “name”: “John Doe”, “age”: 21, “courses”: [“Math”, “Physics”, “Chemistry”], “GPA”: 3.7 } Accessing Dictionary Elements…

  • ASCII ,Uni Code Related Functions in Python

    ASCII Code and Related Functions in Python ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns numerical values to letters, digits, punctuation marks, and other characters. Here’s an explanation of ASCII and Python functions that work with it. ASCII Basics Python Functions for ASCII 1. ord() – Get ASCII value of a…

  • String Alignment and Padding in Python

    String Alignment and Padding in Python In Python, you can align and pad strings to make them visually consistent in output. The main methods used for this are: 1. str.ljust(width, fillchar) Left-aligns the string and fills remaining space with a specified character (default: space). Syntax: python string.ljust(width, fillchar=’ ‘) Example: python text = “Python” print(text.ljust(10)) #…

Leave a Reply

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