Post

10. Python Functions - Advanced

πŸš€ Level up your Python skills! Master advanced function concepts like *args, **kwargs, lambda functions, and recursion. Explore scope, LEGB rule, and more to write cleaner, more efficient code. πŸ’‘

10. Python Functions - Advanced

What we will learn in this post?

  • πŸ‘‰ *args - Variable Length Arguments
  • πŸ‘‰ **kwargs - Keyword Variable Length Arguments
  • πŸ‘‰ Lambda Functions
  • πŸ‘‰ Scope and LEGB Rule
  • πŸ‘‰ global and nonlocal Keywords
  • πŸ‘‰ Recursive Functions
  • πŸ‘‰ Higher-Order Functions
  • πŸ‘‰ Conclusion!

Unpacking Positional Arguments with *args πŸ§™β€β™‚οΈ

Let’s demystify *args! It’s a special syntax in Python that lets you pass a variable number of positional arguments to a function. This powerful feature is essential for building flexible APIs and libraries where you don’t know in advance how many arguments a user might provide. In production code, you’ll find *args used extensively in logging systems, mathematical operations, and data processing pipelines where the number of inputs can vary dynamically. πŸš€

How *args Works βš™οΈ

  • *args collects all the extra positional arguments you pass into a tuple. Think of it as a container!
  • Inside the function, you can iterate through this tuple.

Practical Use Cases 🎯

Summing Numbers βž•

1
2
3
4
5
6
7
8
9
10
def my_sum(*numbers):
  """Calculates the sum of any number of numbers."""
  total = 0
  for number in numbers:
    total += number
  return total

print(my_sum(1, 2, 3))   # Output: 6
print(my_sum(1, 2, 3, 4, 5)) # Output: 15
print(my_sum()) # Output: 0

String Concatenation πŸ”—

1
2
3
4
5
6
7
def string_concat(*words):
    result = ""
    for word in words:
        result += word
    return result

print(string_concat("Hello", " ", "World", "!")) # Output: Hello World!

Real-World Example: Logging System πŸ“

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def log_event(level, *messages):
    """
    Production-ready logging function that accepts variable messages.
    Used in web applications to log events with different detail levels.
    """
    timestamp = "2025-11-06 10:30:45"
    formatted_message = " | ".join(str(msg) for msg in messages)
    print(f"[{timestamp}] [{level}] {formatted_message}")

# Usage in a web application
log_event("INFO", "User login", "username: alice", "IP: 192.168.1.1")
# Output: [2025-11-06 10:30:45] [INFO] User login | username: alice | IP: 192.168.1.1

log_event("ERROR", "Database connection failed", "Retry attempt: 3")
# Output: [2025-11-06 10:30:45] [ERROR] Database connection failed | Retry attempt: 3
πŸš€ Try this Live β†’ Click to open interactive PYTHON playground

Building flexible APIs πŸ› οΈ

Functions can accept a base set of parameters while allowing optional additions.

Understanding **kwargs in Python πŸš€

**kwargs is like a magic keyword in Python! It lets you pass a variable number of keyword arguments (arguments with names, like name="Alice") into a function. This feature is crucial in production environments for creating configurable systems, handling API requests with optional parameters, and building extensible frameworks where users need the flexibility to provide custom options. Think of it as a container for extra, optional settings that makes your code adaptable to changing requirements. 🎯

How It Works (The Dictionary Connection πŸ“š)

When you use **kwargs in a function definition, Python collects all the keyword arguments that aren’t specifically defined and bundles them into a dictionary. The keyword (the name of the argument) becomes the key in the dictionary, and the value you pass becomes the value.

1
2
3
4
def my_function(**kwargs):
  print(kwargs)

my_function(name="Bob", age=30, city="New York") # Output: {'name': 'Bob', 'age': 30, 'city': 'New York'}

When to Use It? (Configuration Example βš™οΈ)

**kwargs is super useful for:

  • Configuration functions: Imagine a function that sets up a program. You might have default settings, but you want users to be able to override them.
1
2
3
4
5
6
7
def configure_settings(**kwargs):
  default_settings = {"theme": "light", "font_size": 12}
  settings = {**default_settings, **kwargs} #merging default with kwargs
  print(f"Current Settings: {settings}")

configure_settings(theme="dark", font_size=14) #Output: Current Settings: {'theme': 'dark', 'font_size': 14}
configure_settings() #Output: Current Settings: {'theme': 'light', 'font_size': 12}

Real-World Example: API Request Handler 🌐

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def send_api_request(endpoint, method="GET", **kwargs):
    """
    Production API client that handles flexible request parameters.
    Used in web applications to communicate with external services.
    """
    base_url = "https://api.example.com"
    headers = kwargs.get("headers", {"Content-Type": "application/json"})
    timeout = kwargs.get("timeout", 30)
    auth = kwargs.get("auth", None)
    
    print(f"Sending {method} request to: {base_url}{endpoint}")
    print(f"Headers: {headers}")
    print(f"Timeout: {timeout}s")
    if auth:
        print(f"Authentication: Enabled")
    if "params" in kwargs:
        print(f"Query Parameters: {kwargs['params']}")
    if "data" in kwargs:
        print(f"Request Body: {kwargs['data']}")

# Usage examples
send_api_request(
    "/users",
    headers={"Authorization": "Bearer token123"},
    params={"page": 1, "limit": 10}
)

send_api_request(
    "/users/create",
    method="POST",
    data={"name": "Alice", "email": "alice@example.com"},
    timeout=60
)
πŸš€ Try this Live β†’ Click to open interactive PYTHON playground

It provides flexibility, allowing users to change only the settings they care about, without needing to specify all possible options.

  • Passing arguments to other functions seamlessly.

Resources:

Lambda Functions: Your Quick Code Helper ⚑

Lambda functions, also called anonymous functions, are like mini-functions in Python. They’re designed for simple tasks where you don’t need a full-blown function definition. In professional development, lambda functions are extensively used in data processing pipelines, GUI event handlers, and functional programming patterns. They help keep your code concise and readable when you need throwaway functions for short operations, making them invaluable tools in production-grade Python applications. πŸš€

What are Lambda Functions?

Think of them as one-line wonders!

  • Syntax: lambda arguments: expression
  • Use: For short, simple operations you want to perform on-the-fly.
  • Limitation: They can only contain a single expression (no complex logic).

Lambda in Action ✨

Here are some examples using map(), filter(), and sorted():

  • map(): Apply a function to each item in a list.

    1
    2
    3
    
    numbers = [1, 2, 3, 4, 5]
    squared = list(map(lambda x: x**2, numbers))
    print(squared) # Output: [1, 4, 9, 16, 25]
    
  • filter(): Select items from a list based on a condition.

    1
    2
    3
    
    numbers = [1, 2, 3, 4, 5, 6]
    even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
    print(even_numbers) # Output: [2, 4, 6]
    
  • sorted(): Sort a list using a custom sorting key.

    1
    2
    3
    
    words = ["apple", "banana", "kiwi"]
    sorted_words = sorted(words, key=lambda x: len(x))
    print(sorted_words) # Output: ['kiwi', 'apple', 'banana']
    

Real-World Example: E-Commerce Product Filtering πŸ›’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Product database for an e-commerce platform
products = [
    {"name": "Laptop", "price": 1200, "category": "Electronics", "rating": 4.5},
    {"name": "Phone", "price": 800, "category": "Electronics", "rating": 4.7},
    {"name": "Desk", "price": 300, "category": "Furniture", "rating": 4.2},
    {"name": "Chair", "price": 150, "category": "Furniture", "rating": 4.0},
    {"name": "Monitor", "price": 400, "category": "Electronics", "rating": 4.6}
]

# Filter electronics over $500
expensive_electronics = list(filter(
    lambda p: p["category"] == "Electronics" and p["price"] > 500, 
    products
))
print("Expensive Electronics:", [p["name"] for p in expensive_electronics])
# Output: ['Laptop', 'Phone']

# Sort products by rating (highest first)
top_rated = sorted(products, key=lambda p: p["rating"], reverse=True)
print("Top Rated:", [f"{p['name']} ({p['rating']}β˜…)" for p in top_rated])
# Output: ['Phone (4.7β˜…)', 'Monitor (4.6β˜…)', 'Laptop (4.5β˜…)', 'Desk (4.2β˜…)', 'Chair (4.0β˜…)']

# Calculate discounted prices (10% off)
discounted_prices = list(map(lambda p: {**p, "discounted_price": p["price"] * 0.9}, products))
for item in discounted_prices[:2]:
    print(f"{item['name']}: ${item['price']} β†’ ${item['discounted_price']:.2f}")
# Output: Laptop: $1200 β†’ $1080.00
#         Phone: $800 β†’ $720.00
πŸš€ Try this Live β†’ Click to open interactive PYTHON playground

Use lambda functions to keep your code clean and readable, especially when dealing with simple, repetitive operations!

More info: Python Lambda Functions

Variable Scope in Python: LEGB Explained πŸ•΅οΈβ€β™€οΈ

Let’s unravel the mystery of variable scope in Python! Variable scope determines where you can access a variable in your code. Understanding scope is critical for writing bug-free applications, especially in large codebases where naming conflicts can cause subtle errors. Python uses the LEGB rule to figure out which variable you’re referring to, ensuring predictable behavior in nested functions, modules, and complex applications. Think of it like a search order that Python follows systematically! πŸ”

The LEGB Rule: Your Variable Detective Kit πŸ”

LEGB stands for:

  • Local: Inside a function.
  • Enclosing function locals: Inside any enclosing functions.
  • Global: At the top level of your script or module.
  • Built-in: Predefined names in Python (like print, len).

Python searches for a variable in this order. If it finds a match, it stops!

Example Time! πŸ’‘

1
2
3
4
5
6
7
8
9
10
11
12
global_var = 10  # Global variable

def outer_function():
    enclosing_var = 20 # Enclosing variable
    def inner_function():
        local_var = 30  # Local variable
        print(local_var, enclosing_var, global_var) # Accessing variables
    inner_function()

outer_function() # Output: 30 20 10
print(global_var)  # Output: 10
#print(local_var) # This would cause an error! local_var is not defined globally
  • global_var is accessible everywhere.
  • enclosing_var is accessible within outer_function and its inner functions.
  • local_var is only accessible within inner_function. Trying to access local_var outside inner_function would result in a NameError.

In a nutshell: Python looks for variables locally first, then in enclosing scopes, then globally, and finally in the built-in namespace. If it doesn’t find the variable anywhere, you’ll get a NameError.

Resource: You can find more information on this topic at Python documentation

Global and Nonlocal Keywords in Python 🌍

Let’s explore how to tweak variables outside of their normal scope! These keywords help us modify variables in the global scope and in enclosing function scopes. While powerful, these features should be used judiciously in production code. In enterprise applications, excessive use of global state can lead to maintenance nightmares and hard-to-trace bugs. However, when used appropriately for configuration management, singleton patterns, or closure-based caching, they become valuable tools in your Python arsenal. 🎯

Understanding global

The global keyword lets you modify a variable that exists outside the current function. Think of it as saying, β€œHey Python, I want to work with the global version of this variable!”

1
2
3
4
5
6
7
8
global_var = 10

def modify_global():
    global global_var  # Declare that we are using the global variable
    global_var = 20

modify_global()
print(global_var) # Output: 20

When to use: If you absolutely need to change a global variable’s value from within a function. It’s generally better to avoid excessive use of global as it can make code harder to understand and debug. Prefer returning values from functions instead.

Understanding nonlocal 🏘️

The nonlocal keyword is for nested functions. It lets you modify a variable in the nearest enclosing scope, which is neither the local scope nor the global scope.

1
2
3
4
5
6
7
8
9
10
11
12
def outer_function():
    outer_var = 10

    def inner_function():
        nonlocal outer_var # Modify outer_var from the outer function
        outer_var = 20
        print("Inner:", outer_var)  # Output: Inner: 20

    inner_function()
    print("Outer:", outer_var)  # Output: Outer: 20

outer_function()

When to use: When you want to modify a variable in an enclosing function’s scope from within a nested function. Similar to global, overuse can make code harder to follow.

Potential Pitfalls

  • Readability: Overusing global and nonlocal can make your code hard to read and understand.
  • Debugging: Changes to variables become harder to trace when their scope is not clearly defined.
  • Side Effects: Modifying global/nonlocal variables can lead to unexpected side effects in other parts of your code.
graph TB
    START["🎯 Function Starts"]:::startStyle --> CHECK_VAR{"Variable Defined?"}:::decisionStyle
    CHECK_VAR -- "Yes" --> CHECK_LOCAL{"Local Scope?"}:::decisionStyle
    CHECK_VAR -- "No" --> ERROR["❌ NameError"]:::errorStyle
    
    CHECK_LOCAL -- "Yes" --> USE_DIRECT["βœ… Use Directly"]:::successStyle
    CHECK_LOCAL -- "No" --> CHECK_ENCLOSING{"Enclosing Scope?"}:::decisionStyle
    
    CHECK_ENCLOSING -- "Yes" --> USE_NONLOCAL["πŸ”§ Use 'nonlocal'"]:::actionStyle
    CHECK_ENCLOSING -- "No" --> CHECK_GLOBAL{"Global Scope?"}:::decisionStyle
    
    CHECK_GLOBAL -- "Yes" --> USE_GLOBAL["🌍 Use 'global'"]:::actionStyle
    CHECK_GLOBAL -- "No" --> ERROR
    
    USE_DIRECT --> END["✨ Variable Accessed"]:::endStyle
    USE_NONLOCAL --> END
    USE_GLOBAL --> END
    
    classDef startStyle fill:#43e97b,stroke:#38f9d7,color:#000,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef decisionStyle fill:#ffd700,stroke:#d99120,color:#222,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef successStyle fill:#00bfae,stroke:#005f99,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef actionStyle fill:#6b5bff,stroke:#4a3f6b,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef errorStyle fill:#ff4f81,stroke:#c43e3e,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef endStyle fill:#ff9800,stroke:#f57c00,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    
    linkStyle default stroke:#e67e22,stroke-width:3px;

Resources:Python global Keyword, Python nonlocal Keyword

Recursion Explained πŸ”„

Recursion is a programming technique where a function calls itself to solve a problem. Think of it like Russian nesting dolls 🧸 - each doll contains a smaller version of itself! In professional software development, recursion is essential for solving problems with hierarchical or tree-like structures, such as file system traversal, organizational charts, parsing nested data structures like JSON and XML, and implementing divide-and-conquer algorithms. While elegant for certain problems, understanding when to use recursion versus iteration is crucial for writing efficient, production-grade code.

How it Works: Calling Itself! πŸ“ž

A recursive function has two key parts:

  • Base Case: The condition where the function stops calling itself. This is essential to prevent an infinite loop (like those dolls that never end!).
  • Recursive Case: The function calls itself with a slightly smaller version of the original problem, moving closer to the base case.
graph TB
    START["🎯 Function Called<br/>with n"]:::startStyle --> BASE_CHECK{"Base Case<br/>Reached?"}:::decisionStyle
    
    BASE_CHECK -- "Yes" --> RETURN_BASE["βœ… Return Base Value"]:::successStyle
    BASE_CHECK -- "No" --> RECURSIVE["πŸ”„ Call Function<br/>with n-1"]:::recursiveStyle
    
    RECURSIVE --> SMALLER["⬇️ Problem Gets<br/>Smaller"]:::processStyle
    SMALLER --> BASE_CHECK
    
    RETURN_BASE --> COMBINE["πŸ”— Combine Results"]:::combineStyle
    COMBINE --> FINAL["✨ Final Result"]:::endStyle
    
    classDef startStyle fill:#43e97b,stroke:#38f9d7,color:#000,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef decisionStyle fill:#ffd700,stroke:#d99120,color:#222,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef successStyle fill:#00bfae,stroke:#005f99,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef recursiveStyle fill:#ff4f81,stroke:#c43e3e,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef processStyle fill:#6b5bff,stroke:#4a3f6b,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef combineStyle fill:#9e9e9e,stroke:#616161,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    classDef endStyle fill:#ff9800,stroke:#f57c00,color:#fff,font-size:16px,stroke-width:3px,rx:14,shadow:6px;
    
    linkStyle default stroke:#e67e22,stroke-width:3px;

Examples

  • Factorial: Calculating n! (n * (n-1) * ... * 1)

    1
    2
    3
    4
    5
    6
    7
    
    def factorial(n):
        if n == 0:  # Base Case: Factorial of 0 is 1
            return 1
        else:        # Recursive Case: Call factorial with n-1
            return n * factorial(n-1)
    
    print(factorial(5)) # Output: 120
    
  • Fibonacci Sequence: Generating the sequence 0, 1, 1, 2, 3, 5, 8, ...

    1
    2
    3
    4
    5
    6
    7
    
    def fibonacci(n):
        if n <= 1:  # Base Case: Fibonacci of 0 or 1
            return n
        else:        # Recursive Case: Sum of previous two Fibonacci numbers
            return fibonacci(n-1) + fibonacci(n-2)
    
    print(fibonacci(6)) # Output: 8
    

Real-World Example: File System Traversal πŸ“

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import os

def count_files_recursive(directory):
    """
    Production-ready function to count files in a directory tree.
    Used in backup systems, file management tools, and cloud storage apps.
    """
    file_count = 0
    
    try:
        # List all items in the directory
        for item in os.listdir(directory):
            item_path = os.path.join(directory, item)
            
            if os.path.isfile(item_path):
                file_count += 1  # Base case: it's a file
            elif os.path.isdir(item_path):
                # Recursive case: it's a directory, count files inside it
                file_count += count_files_recursive(item_path)
    except PermissionError:
        print(f"Permission denied: {directory}")
    
    return file_count

# Usage example
# total_files = count_files_recursive("/home/user/documents")
# print(f"Total files found: {total_files}")
πŸš€ Try this Live β†’ Click to open interactive PYTHON playground

Recursion vs. Iteration πŸ€”

Recursion can be elegant and easier to read for certain problems. However, it can sometimes be less efficient than iteration (using loops) due to the overhead of function calls. Choose recursion when it simplifies the code and makes it more understandable, but be mindful of performance implications.

Higher-Order Functions: Functions that Play with Functions πŸ§‘β€πŸ’»

Higher-order functions are functions that either accept other functions as arguments or return other functions as their result. This powerful concept is fundamental to functional programming and is widely used in production environments for data transformation pipelines, event-driven architectures, middleware systems, and decorator patterns. Understanding higher-order functions enables you to write more modular, reusable, and testable code that scales well in enterprise applications. Think of it like functions calling other functions to perform operations or return a function object. πŸš€

The Dynamic Trio: map(), filter(), reduce() βš™οΈ

Python offers some built-in higher-order functions. Let’s explore three common ones: map(), filter(), and reduce() (from the functools module).

  • map(): Applies a function to each item in an iterable (like a list) and returns a new iterator with the results.
  • filter(): Creates a new iterator with items from an iterable for which a function returns True.
  • reduce(): Applies a function cumulatively to the items of an iterable, reducing it to a single value (needs importing from functools).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from functools import reduce

numbers = [1, 2, 3, 4, 5]

# Using map() to square each number
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]

# Using filter() to get even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]

# Using reduce() to find the product of all numbers
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 120

Practical Use Cases πŸš€

Imagine processing a list of usernames to capitalize them, selecting valid emails from a database or calculating the total value of items in a shopping cart. Higher-order functions let you perform these actions concisely and elegantly.

1
2
3
names = ["alice", "bob", "charlie"]
capitalized_names = list(map(lambda name: name.capitalize(), names))
print(capitalized_names) # Output: ['Alice', 'Bob', 'Charlie']

Real-World Example: Data Processing Pipeline πŸ“Š

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from functools import reduce

# User transaction data from an e-commerce platform
transactions = [
    {"user_id": 101, "amount": 250.00, "status": "completed"},
    {"user_id": 102, "amount": 450.00, "status": "completed"},
    {"user_id": 103, "amount": 120.00, "status": "pending"},
    {"user_id": 101, "amount": 380.00, "status": "completed"},
    {"user_id": 104, "amount": 90.00, "status": "failed"},
    {"user_id": 102, "amount": 200.00, "status": "completed"},
]

# Production-grade data pipeline using higher-order functions

# Step 1: Filter only completed transactions
completed = list(filter(lambda t: t["status"] == "completed", transactions))
print(f"Completed transactions: {len(completed)}")

# Step 2: Extract amounts with tax calculation (10%)
amounts_with_tax = list(map(lambda t: t["amount"] * 1.10, completed))
print(f"Amounts with tax: {[f'${amt:.2f}' for amt in amounts_with_tax]}")

# Step 3: Calculate total revenue using reduce
total_revenue = reduce(lambda acc, t: acc + t["amount"], completed, 0)
print(f"Total revenue: ${total_revenue:.2f}")

# Step 4: Group transactions by user (using higher-order approach)
def group_by_user(transactions):
    from collections import defaultdict
    grouped = defaultdict(list)
    for t in transactions:
        grouped[t["user_id"]].append(t["amount"])
    return dict(grouped)

user_spending = group_by_user(completed)
print(f"User spending: {user_spending}")

# Step 5: Find top spender using max with key function
top_spender = max(user_spending.items(), key=lambda item: sum(item[1]))
print(f"Top spender: User {top_spender[0]} spent ${sum(top_spender[1]):.2f}")

# Output:
# Completed transactions: 4
# Amounts with tax: ['$275.00', '$495.00', '$418.00', '$220.00']
# Total revenue: $1280.00
# User spending: {101: [250.0, 380.0], 102: [450.0, 200.0]}
# Top spender: User 102 spent $650.00
πŸš€ Try this Live β†’ Click to open interactive PYTHON playground

More information on Higher-Order Functions


🎯 Practice Project Assignment

πŸ’‘ Project: Advanced Function Toolkit - Build a Multi-Purpose Utility Library (Click to expand)

Your Challenge:

Create a comprehensive Python utility library that combines *args, **kwargs, lambda functions, recursion, and higher-order functions to solve real-world data processing problems.

Implementation Hints:

  • Step 1: Create a flexible logger function using *args that accepts multiple messages and optional keyword arguments for log level and timestamp formatting. Example: log("User action", "Login successful", level="INFO")
  • Step 2: Build a configuration merger using **kwargs that combines default settings with user-provided overrides, similar to the API request handler we learned. Test with nested dictionaries.
  • Step 3: Implement data filtering and transformation using lambda functions - create filters for even/odd numbers, string length validation, and custom sorting keys for complex data structures.
  • Step 4: Add a recursive directory tree printer that displays nested folder structures with proper indentation (similar to the file system traversal example but with visual formatting).
  • Step 5: Create a data processing pipeline using map, filter, and reduce to calculate statistics (mean, median, sum) from a list of transaction dictionaries.
  • Bonus Challenge: Combine everything into a single utility class with methods that demonstrate all advanced function concepts. Add error handling and docstrings for production-ready code!

Example Output:

=== ADVANCED FUNCTION TOOLKIT DEMO ===
[2025-11-06 14:30:00] [INFO] Application started | User: admin
[2025-11-06 14:30:01] [DEBUG] Processing request | Endpoint: /api/users

Configuration merged successfully:
{'theme': 'dark', 'timeout': 60, 'debug': True}

Filtered even numbers: [2, 4, 6, 8, 10]
Sorted by length: ['cat', 'bird', 'elephant']

Directory Tree:
πŸ“ project/
  πŸ“ src/
    πŸ“„ main.py
    πŸ“„ utils.py
  πŸ“ tests/
    πŸ“„ test_main.py

Transaction Statistics:
  Total: $1,280.00
  Count: 4 transactions
  Average: $320.00
  Top user: User 102 ($650.00)

Share Your Solution! πŸ’¬

Got your utility library working? Awesome! Share your code in the comments below - we'd love to see how you combined these advanced concepts! Feel free to add your own creative functions or modify the examples to match your interests. The best way to learn is by building and sharing! πŸš€


Conclusion

So there you have it! We hope you enjoyed this post and found it helpful οΏ½. We’re always looking to improve, so we’d love to hear your thoughts! What did you think? Anything you’d like to see more of? Let us know in the comments below πŸ‘‡. Your feedback is super valuable to us! Let’s keep the conversation going! πŸŽ‰

This post is licensed under CC BY 4.0 by the author.