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

  • Special Sequences in Python

    Special Sequences in Python Regular Expressions – Detailed Explanation Special sequences are escape sequences that represent specific character types or positions in regex patterns. 1. \A – Start of String Anchor Description: Matches only at the absolute start of the string (unaffected by re.MULTILINE flag) Example 1: Match only at absolute beginning python import re text = “Start here\nStart…

  • file properties and methods

    1. file.closed – Is the file door shut? Think of a file like a door. file.closed tells you if the door is open or closed. python # Open the file (open the door) f = open(“test.txt”, “w”) f.write(“Hello!”) print(f.closed) # Output: False (door is open) # Close the file (close the door) f.close() print(f.closed) # Output: True (door is…

  • difference between positional and keyword arguments

    1. Positional Arguments How they work: The arguments you pass are matched to the function’s parameters based solely on their order (i.e., their position). The first argument is assigned to the first parameter, the second to the second, and so on. Example: python def describe_pet(animal_type, pet_name): “””Display information about a pet.””” print(f”\nI have a {animal_type}.”) print(f”My {animal_type}’s name…

  • replace(), join(), split(), rsplit(), and splitlines() methods in Python

    1. replace() Method Purpose: Replaces occurrences of a substring with another substring.Syntax: python string.replace(old, new[, count]) Examples: Example 1: Basic Replacement python text = “Hello World” new_text = text.replace(“World”, “Python”) print(new_text) # Output: “Hello Python” Example 2: Limiting Replacements (count) python text = “apple apple apple” new_text = text.replace(“apple”, “orange”, 2) print(new_text) # Output: “orange orange apple”…

  • Password Strength Checker

    python Enhanced Password Strength Checker python import re def is_strong(password): “”” Check if a password is strong based on multiple criteria. Returns (is_valid, message) tuple. “”” # Define criteria and error messages criteria = [ { ‘check’: len(password) >= 8, ‘message’: “at least 8 characters” }, { ‘check’: bool(re.search(r'[A-Z]’, password)), ‘message’: “one uppercase letter (A-Z)”…

  • Create a User-Defined Exception

    A user-defined exception in Python is a custom error class that you create to handle specific error conditions within your code. Instead of relying on built-in exceptions like ValueError, you define your own to make your code more readable and to provide more specific error messages. You create a user-defined exception by defining a new…

Leave a Reply

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