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

  • For loop 13 and 14th class

    The range() Function in Python The range() function is a built-in Python function that generates a sequence of numbers. It’s commonly used in for loops to iterate a specific number of times. Basic Syntax There are three ways to use range(): 1. range(stop) – One Parameter Form Generates numbers from 0 up to (but not including) the stop value. python for i in range(5):…

  • Python Statistics Module

    Python Statistics Module: Complete Methods Guide with Examples Here’s a detailed explanation of each method in the Python statistics module with 3 practical examples for each: 1. Measures of Central Tendency mean() – Arithmetic Average python import statistics as stats # Example 1: Basic mean calculation data1 = [1, 2, 3, 4, 5] result1 = stats.mean(data1) print(f”Mean of…

  • Thonny: A User-Friendly Python IDE for Beginners in 2025

    Thonny is a free and open-source Integrated Development Environment (IDE) specifically designed for beginners learning Python. It provides a simple and user-friendly interface, making it an excellent choice for those new to programming. Key Features: Why Thonny is good for beginners: How to install Thonny: If you’re new to Python and looking for a user-friendly…

  • Global And Local Variables

    Global Variables In Python, a global variable is a variable that is accessible throughout the entire program. It is defined outside of any function or class. This means its scope is the entire file, and any function can access and modify its value. You can use the global keyword inside a function to modify a…

  • Real-World Applications of Python Lists

    Python lists and their methods are used extensively in real-time applications across various domains. They are fundamental for organizing and manipulating ordered collections of data. Real-World Applications of Python Lists 1. Web Development In web development, lists are crucial for handling dynamic data. For example, a list can store user comments on a post, products…

  • Functions as Objects

    Functions as Objects and First-Class Functions in Python In Python, functions are first-class objects, which means they can be: 1. Functions as Objects In Python, everything is an object, including functions. When you define a function, you’re creating a function object. python def greet(name): return f”Hello, {name}!” # The function is an object with type ‘function’…

Leave a Reply

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