Fundamentals 8 min read

Python Function Fundamentals: Arguments, Lambdas, Decorators, and Advanced Techniques

This tutorial showcases Python function fundamentals such as default and keyword arguments, *args and **kwargs, lambda expressions, higher‑order functions, decorators (with and without parameters), closures, scope modifiers, type hints, and utility modules like functools, inspect, and operator, providing concise code examples for each concept.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Function Fundamentals: Arguments, Lambdas, Decorators, and Advanced Techniques

This article demonstrates a wide range of Python function features, starting with default parameter values and keyword arguments, illustrating how to define functions with optional defaults and how to call them using explicit parameter names.

def greet(name, message="你好"):
    # Print greeting with default message
    print(f"{name}, {message}")

greet("张三")  # Output: 张三, 你好

It then shows how to collect arbitrary positional arguments using *args and keyword arguments using **kwargs , enabling flexible function signatures.

def make_pizza(*toppings):
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

def build_profile(first, last, **user_info):
    profile = {'first_name': first, 'last_name': last}
    profile.update(user_info)
    return profile

print(build_profile('albert', 'einstein', location='princeton', field='physics'))

Lambda expressions are introduced for concise anonymous functions, including their use with sorted and as arguments to higher‑order functions.

add = lambda x, y: x + y
print(add(5, 3))  # 8

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
sorted_pairs = sorted(pairs, key=lambda pair: pair[1])
print(sorted_pairs)

Higher‑order functions are illustrated by passing functions as arguments and returning functions from other functions, such as a multiplier factory.

def operation(x, y, func):
    return func(x, y)

print(operation(10, 5, lambda a, b: a - b))  # 5

def make_multiplier_of(n):
    def multiplier(x):
        return x * n
    return multiplier

times3 = make_multiplier_of(3)
print(times3(9))  # 27

Decorator usage is covered, including simple decorators, decorators with parameters, and preserving metadata with functools.wraps .

def decorator_function(original_function):
    def wrapper_function():
        print('在调用之前执行一些操作')
        return original_function()
    return wrapper_function

@decorator_function
def display():
    print('display function ran')

display()

def prefix_decorator(prefix):
    def decorator(original_function):
        def new_function():
            print(f"{prefix} 在原始函数前执行")
            return original_function()
        return new_function
    return decorator

@prefix_decorator("LOG:")
def say_hello():
    print("Hello!")

say_hello()

from functools import wraps

def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        print("Calling function.")
        return f(*args, **kwargs)
    return wrapper

@my_decorator
def example():
    """Docstring"""
    print("Inside example function")

print(example.__name__)  # example
print(example.__doc__)   # Docstring

Scope manipulation with global and nonlocal keywords is shown, as well as introspection tools like inspect.signature and locals() .

global_var = 0

def update_global():
    global global_var
    global_var += 1

update_global()
print(global_var)  # 1

def outer():
    x = "local"
    def inner():
        nonlocal x
        x = 'nonlocal'
        print('inner:', x)
    inner()
    print('outer:', x)

outer()

import inspect

def foo(a, b=2, *args, **kwargs):
    pass

sig = inspect.signature(foo)
print(sig)  # (a, b=2, *args, **kwargs)

def show_locals():
    x = 1
    y = 2
    print(locals())

show_locals()

Functional utilities such as map , filter , reduce , and the operator module replace explicit loops and lambda expressions for common operations.

numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16]

even_numbers = list(filter(lambda x: x % 2 == 0, range(10)))
print(even_numbers)  # [0, 2, 4, 6, 8]

from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4])
print(product)  # 24

import operator
sum_result = reduce(operator.add, numbers)
print(sum_result)  # 10

Additional advanced topics include dynamic code execution with exec , creating context managers via contextlib.contextmanager , type hints, and using functools.partial to fix function arguments.

code = "a = 5\nb = 6\nprint('a + b =', a + b)"
exec(code)  # a + b = 11

from functools import partial
def multiply(a, b):
    return a * b

double = partial(multiply, 2)
print(double(5))  # 10

from contextlib import contextmanager
@contextmanager
def tag(name):
    print(f"<{name}>")
    yield
    print(f"
")

with tag('h1'):
    print('标题文本')

def greeting(name: str) -> str:
    return 'Hello, ' + name

print(greeting('world'))  # Hello, world

Finally, examples of recursion (factorial), list comprehensions combined with functions, and documenting functions with docstrings are provided.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))  # 120

def square(x):
    return x*x
numbers = [1, 2, 3, 4]
squares = [square(num) for num in numbers]
print(squares)  # [1, 4, 9, 16]

def doc_example():
    """
    这是一个带有文档字符串的例子。
    它描述了函数的功能、参数和返回值。
    """
    pass

print(doc_example.__doc__)
lambdaFunctionsdecoratorsClosuresAdvancedarguments
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.