Functions - Additional Topics#

This notebook presents additional, miscellaneous topics related to functions.

Packing and Unpacking Arguments#

In Python, the asterisk * is used for packing and unpacking arguments, which allows for more flexible argument passing to functions.

Positional#

When defining a function, use *args to pack all positional arguments into a tuple. This is useful when you don’t know how many arguments will be passed to your function.

1def pack_args(*args):
2    print("Number of arguments:", len(args))
3    for index, item in enumerate(args):
4        print("{}: {}".format(index,item))
5
6pack_args(1, 2, 3, 4)  # Output: (1, 2, 3, 4)
Number of arguments: 4
0: 1
1: 2
2: 3
3: 4

You can mix regular arguments with *args in function definitions. Regular arguments are assigned first, and the rest are captured by *args.

1def mixed_arguments(first, *args):
2    print("First argument:", first)
3    print("Other arguments:", args)
4
5mixed_arguments(1, 2, 3, 4)  
First argument: 1
Other arguments: (2, 3, 4)

Keyword#

While *args packs positional arguments, **kwargs packs keyword arguments, which are placed into a dictionary.

1def greet_all(**kwargs):
2    for key, value in kwargs.items():
3        print("{}: {}".format(key,value))
4
5greet_all(John="Hello", Alice="Hi")
John: Hello
Alice: Hi

Unpacking (exploding) Arguments#

Outside of a function definition, we can use * and ** to unpack (explode) arguments to be sent to a function.

1def greet(first, last):
2    print("Hello {} {}!".format(first,last))
3
4alist = ['Condoleezza','Rice']
5adict = {'first': 'Edward', 'last': 'Sorin' }
6greet(*alist)
7greet(**adict)
Hello Condoleezza Rice!
Hello Edward Sorin!

Pass by Reference#

As a reminder, everything in Python is an object. When we pass arguments to a function, the reference to the object is passed. So if a mutable object is passed to a function, any changes to that object within the function will be reflected outside of the function.

In Python, a side effect refers to any change that a function makes to its state or the global program state, in addition to its return value. Typically, side effects emerge from modifying a global variables or changing mutatable arguments (e.g., a list or dictionary passed to a function).

An interesting case arises when a mutable object is used a default parameter. In the following function f, a naive reading would assume that a new list is created everytime f is called.

1def f(a = [], b = 2.34 * 500):
2    a.append("test")
3    print("b's identifier: ", id(b))
4    return a

In actuality, the Python interpreter only evaluates the default arguments once - most likely when the function itself is evaluated and then stored for future use.

1print(f())
2print(f())
b's identifier:  4435515504
['test']
b's identifier:  4435515504
['test', 'test']

Since the identifier for b remains constant, we can safely conclude that the interpreter only evaluates the expression 2.34 * 500 once. That expression was explicitly chosen over something like 1, which the Python intrepeter optimizes for performance.

Also, you’ll see that the side effect of appending “test” to a occurs and that the default value for a remains unchanged through subsequent calls.

Functions are First-class Citizens#

Since everything in Python is an object, functions are also objects. Primarily, this means we can assign functions to varables. In turn, this allows us to store them in functions, pass them as arguments, and return them from functions.

1 def greet(name):
2    return "Hello, {}!".format(name)
3
4greet_function = greet
5print(greet_function("Alice")) 
  Cell In[7], line 1
    def greet(name):
    ^
IndentationError: unexpected indent
 1def shout(text):
 2    return text.upper()
 3
 4def whisper(text):
 5    return text.lower()
 6
 7def greet(style, name):
 8    return style(name)
 9
10print(greet(shout, "Hello"))
11print(greet(whisper, "Hello"))
HELLO
hello

Inner functions#

As we saw in the Recursion notebook with wrapper functions, we can define a function within another function. These functions are often used for organization, encapsulation, or to create closures. In a future notebook, We’ll also see how they are used to create decorators.

 1def outer_function(text):
 2    # This is the outer enclosing function
 3
 4    def inner_function():
 5        # This is the nested inner function
 6        return text.upper()
 7
 8    # The outer function returns the result of the inner function
 9    return inner_function()
10
11result = outer_function("hello")
12print(result) 
HELLO

Closures#

Inner functions can also create closures in Python. A closure in Python is a function object that remembers values in enclosing scopes. It’s a record that stores a function together with an environment: a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. A closure occurs when:

  1. A nested function references a value in its enclosing scope.

  2. The enclosing function returns the nested function.

 1def outer_function(text):
 2    
 3    def inner_function():
 4        return text
 5
 6    return inner_function
 7
 8# Create a closure
 9my_closure = outer_function("Hello, world!")
10print(my_closure())
Hello, world!

Key Points of a Closure

  1. Enclosure: The inner function inner_function is enclosed within the scope of outer_function.

  2. Environment: inner_function remembers the environment in which it was created. In this case, it remembers the value of the variable text.

  3. Persistence: Even after outer_function has finished executing, my_closure retains the information about the variable text.

Advantages of Closures

  1. Data Hiding: Closures can prevent data from being modified unintentionally.

  2. Function Factories: Closures can generate functions tailored to specific needs.

  3. Maintaining State: Closures can persist state across function calls without using global variables.

Function Factory#

Suppose we want to create a function that multiplies a number by a specific factor. We can use a closure to create a factory for such functions:

 1def multiplier_factory(n):
 2    def multiplier(x):
 3        return x * n
 4    return multiplier
 5
 6double = multiplier_factory(2)
 7triple = multiplier_factory(3)
 8
 9print(double(5)) 
10print(triple(5)) 
10
15

Default Arguments#

Default arguments in Python are extremely important because they provide a way to implement method overloading functionality, which isn’t directly supported in the language. They allow you to define parameters with default values. If a caller doesn’t provide these arguments, the default values are used instead.

1def greet(name, greeting="Hello"):
2    return f"{greeting}, {name}!"
3
4# These calls are equivalent
5greet("Alice", "Hi")  # Hi, Alice!
6greet("Alice")        # Hello, Alice!
'Hello, Alice!'

Key Benefits of Default Arguments for “Overloading”

  • API Flexibility: Users can call your function with only the parameters they need

  • Backward Compatibility: You can add new parameters without breaking existing code

  • Simpler Interfaces: Related functionality stays in one function instead of being spread across multiple functions

  • Progressive Disclosure-: Simple use cases remain simple while complex options are available when needed

Best Practices

  • Use immutable objects as defaults: Avoid mutable defaults such as lists or dictionaries. Default arguments are only evaluated once when the Python Interpreter first loads the file.

    # BAD: Mutable default
    def add_item(item, items=[]):  # This can cause unexpected behavior!
        items.append(item)
        return items
    
    # GOOD: Use None and create the list inside. Uses a docstring to highlight the intention to other developers
    def add_item(item, items=None):
        """
        Adds an item to a list. If the list is None, it initializes it.
        Args:
            item: The item to add.
            items (list, optional): The list to which the item will be added. If None, 
                  a new list will be created.
        Returns:
            list: The list containing the added item.
        """
        if items is None:
            items = []
        items.append(item)
        return items
    
  • Avoid dynamic values as defaults: Similarly, avoid using objects that may have default values, but whose values we expect to change on each function call. Consider this method to log responsed from a REST API service call:

    from datetime import datetime
    def log_response(response, when=datetime.now()):
        """
        Logs the response from a REST API to a file.
      
        Args:
            response (requests.Response): The response object from the request.
            when (datetime, optional): The time when the response was received. Defaults to current time. <- WRONG!!!
        """
        with open("ollama_response.log", "a") as log_file:
            log_file.write(f"{when}: {response.status_code}\n")
            log_file.write(f"Response: {response.text}\n\n")
    

    Every call to log_response uses the same value for when.

    Use the same pattern as mutable objects:

    from datetime import datetime
    def log_response(response, when=None):
        """
        Logs the response from a REST API to a file.
      
        Args:
            response (requests.Response): The response object from the request.
            when (str, optional): The time when the response was received. If None, the current time is used.
        """
        if when is None:
            when = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with open("ollama_response.log", "a") as log_file:
            log_file.write(f"{when}: {response.status_code}\n")
            log_file.write(f"Response: {response.text}\n\n")
    
  • Use None as a sentinel value: Allows distinguishing between “not provided” and “explicitly provided as None”

  • Document parameter behavior: Make it clear which parameters are optional and what their defaults mean