Function in Python

A function in Python is a block of organized, reusable code that performs a specific task. Functions are fundamental building blocks in programming, allowing for code modularity, reusability, and maintainability. They can accept parameters, return values, and are essential for creating modular and maintainable code. Functions in Python are first-class objects, meaning they can be passed around and used as arguments, stored in data structures, and returned from other functions. This allows for the creation of higher-order functions and supports functional programming paradigms.

Overview

Functions in Python are defined using the def keyword, followed by the function name and parentheses containing any parameters. The body of the function contains the code that performs a specific task, and it can return a value using the return statement. Functions can return zero, one, or multiple values, and a function that doesn't explicitly return a value will return None. Functions should ideally serve a single purpose, and returning one value is preferred to avoid confusion.

Functions can be enhanced with decorators to add additional behavior, such as logging or performance monitoring, without altering their core functionality. They are also essential in creating APIs (Application Programming Interfaces) and should adhere to the single responsibility principle, meaning each function should perform one specific task.

Defining and Calling Functions

Functions are defined using the def keyword, followed by the function name and parentheses containing any parameters. They can be called with arguments to execute their code. Functions can have default values for arguments, which allows for calling functions with fewer arguments, using preset values instead. This reduces the number of arguments needed and enhances convenience.

Example of a Function with Default Arguments

def complete_task(task, note=""):
   task.status = "completed"
   task.note = note
   print(f"{task.title}'s status: completed; note: {note}")

Figure 6.1 Figure 6.1 An example of the general process of creating a function with default arguments.

Custom Functions and Sorting

Custom functions can be used in sorting to define specific orders by extracting values from each item in a list. This function is set to the key parameter in the sort method. For example, a custom function using_urgency_level can be defined to extract the 'urgency' value from a dictionary for sorting purposes.

Lambda Functions

A lambda function is an anonymous function defined using the lambda keyword. It can be used as a concise way to define a function for the key parameter in sorting. For example:

tasks.sort(key=lambda x: x['urgency'], reverse=True)

This sorts tasks by urgency using a lambda function.

Type Hinting

Type hinting in functions specifies the expected data types for parameters and return values, enhancing code readability and reducing errors. This is particularly useful in larger codebases where understanding the expected input and output types can prevent bugs.

Example of Using Type Hints

from statistics import mean, stdev

def generate_stats(measures: list) -> tuple:
   measure_mean = mean(measures)
   measure_std = stdev(measures)
   return measure_mean, measure_std

Figure 6.4 Figure 6.4 Pop-up menus are shown for functions with type hints in the Python editor PyCharm.

Positional and Keyword Arguments

Functions in Python can be defined to accept a fixed number of arguments or a variable number of arguments using *args and **kwargs. Positional arguments are matched by position, while keyword arguments are matched by name.

Figure 6.6 Figure 6.6 Using positional and keyword arguments in function calls.

Docstrings

Functions can be documented using docstrings to provide information on their usage. When writing docstrings, include a summary of the function's purpose, document each parameter with its name, type, and description, specify the return value, and list any exceptions that the function might raise.

Example of a Docstring

def quotient(dividend, divisor, taking_int=False):
    """
    Calculate the product of two numbers with a base factor.
 
    :param dividend: int | float, the dividend in the division
    :param divisor: int | float, the divisor in the division
    :param taking_int: bool, whether only taking the integer part of 
    ➥  the quotient; default: False, which calculates the 
    ➥  precise quotient of the two numbers
 
    :return: float | int, the quotient of the dividend and divisor
    """
    result = dividend / divisor
    if taking_int:
        result = int(result)
    return result

Functions as Objects

In Python, functions are treated as objects, which means they can be stored in data containers, passed as arguments to other functions, and returned as values from functions. This allows for flexible and dynamic programming patterns.

Example of Functions in a Dictionary

actions = {"mean": get_mean, "min": get_min, "max": get_max}
 
def fallback_action(data):         #1
    return "error in action"
 
def process_data(data, action):
    calculation = actions.get(action, fallback_action)
    processed = calculation(data)
    return processed
#1 The fallback function is called when none of the defined actions are used.

Testing Functions

Testing functions involves providing specific input and verifying that the output matches the expected result. This process can be automated using tools like the unittest module in Python. Creating a TestCase subclass involves inheriting from the unittest.TestCase class and defining test methods within it. These methods should start with the test_ prefix to be recognized as tests.

Example of a Function to be Tested

class Task:                               #1
    def __init__(self, title, urgency):
        self.title = title
        self.urgency = urgency
 
def create_task(text):
    title, urgency_text = text.split(",")
    urgency = int(urgency_text)
    task = Task(title, urgency)
    return task
#1 Creates a custom class

Functions are a fundamental part of Python programming, providing a way to encapsulate code for reuse, testing, and organization. Understanding their capabilities and how to effectively use them is crucial for any Python developer.

| Book Title | Usage of function | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|-------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Python How-To](https://www.manning.com/books/python-how-to) | Functions are described as reusable code blocks that can accept parameters and return values. They are first-class objects and can be enhanced with decorators. | Discusses first-class functions, decorators, and type hinting. | Connects to functional programming paradigms and modular code design. | Includes examples of functions with default arguments, lambda functions, and type hints. | Practical applications include sorting with custom functions and testing functions. [more](https://livebook.manning.com/book/python-how-to/chapter-6/1) |
| [Tiny Python Projects: Learn coding and testing with puzzles and games](https://www.manning.com/books/tiny-python-projects) | Functions are used for modularity and reusability, defined with `def` and can return values. | Focuses on writing and testing functions. | Emphasizes testing with frameworks like `pytest`. | Provides examples like the `greet` and `verse()` functions. | Demonstrates testing functions and generating song verses. [more](https://livebook.manning.com/book/tiny-python-projects/chapter-11/1) |
| [A Pythonic Adventure: From Python basics to a working web app](https://www.manning.com/books/a-pythonic-adventure) | Functions are reusable code blocks for specific tasks, defined with `def`. | Covers basic to advanced function usage, including file reading and database interaction. | Links to file handling, database operations, and web applications. | Examples include menu creation and reading from files. | Practical use in creating menus and interacting with databases. [more](https://livebook.manning.com/book/a-pythonic-adventure/chapter-7/1) |
| [Practices of the Python Pro](https://www.manning.com/books/practices-of-the-python-pro) | Functions are used for modularity, breaking down complex problems. | Discusses function size, responsibility, and extracting functions. | Connects to concepts like cyclomatic complexity and separation of concerns. | Examples include JSON/XML formatting and rock-paper-scissors game. | Practical applications in service endpoints and game logic. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-2/79) |
| [The Well-Grounded Python Developer: How the pros use Python and Flask](https://www.manning.com/books/the-well-grounded-python-developer) | Functions create a namespace for variable scope and are essential for APIs. | Emphasizes single responsibility and idempotency. | Relates to API design and scope management. | Example of `full_name_and_print` function demonstrating single responsibility. | Focus on API design and function testing. [more](https://livebook.manning.com/book/the-well-grounded-python-developer/chapter-2/138) |
| [Python Concurrency with asyncio](https://www.manning.com/books/python-concurrency-with-asyncio) | Functions can be regular or coroutines, crucial for asynchronous programming. | Explores the `TaskRunner` class for managing functions and coroutines. | Connects to asynchronous programming and `asyncio` library. | Example of `TaskRunner` class handling both functions and coroutines. | Practical use in managing concurrency with `asyncio`. [more](https://livebook.manning.com/book/python-concurrency-with-asyncio/chapter-14/15) |
| [Classic Computer Science Problems in Python](https://www.manning.com/books/classic-computer-science-problems-in-python) | Functions are used to implement algorithms and solve computational tasks. | Discusses recursive and iterative approaches. | Connects to algorithm design and computational efficiency. | Examples include recursive and iterative Fibonacci functions. | Practical application in solving classic computer science problems. [more](https://www.manning.com/books/classic-computer-science-problems-in-python) |

FAQ (Frequently asked questions)

How do functions return values in Python?

Where do functions exist in Python?

What do functions do with inputs and outputs?

What does a Python function return if no return statement is specified?

What is the purpose of a docstring in a Python function?

What is the purpose of the fact function in Python?

How do you return a value from a Python function?

Do the number of arguments need to match the number of parameters in Python functions?

Where must default values be specified in a Python function?

What does *args do in a Python function?

What does **kwargs do in a Python function?

How can a Python function handle an indefinite number of keyword arguments?

What are some potential drawbacks of using AI tools for Python code refactoring?

How can a Python function access external variables?