Types of Functions in Python: A Concise Guide
Table of Contents
Functions are one of the most versatile tools in any Python programmer's toolbox. They enable code reuse and provide a form of abstraction. Python offers many different types of functions. This article is a map of the different types you'll encounter as a Python developer.
Regular Functions
The Python functions guide covers definitions, calls, parameters, print() vs. return, None, and scope. Python also supports default parameters for optional arguments and can return multiple values.
Subroutines
A subroutine is a function that doesn't return a value. It performs a task, and that task can be an effect. After execution, it gives control back to the caller.
def sub(x):
print(f"The square of {x} is {x * x}")
sub(2)
# The square of 2 is 4
Pure and Impure Functions
Pure functions are functions with no side effects. They are similar to functions in mathematics. They take in an input and produce an output without altering any external states.
That makes them easy to test and predictable. Pure functions are widely used in functional programming.
Impure functions perform side effects. You'll often encounter side effects like HTTP requests, printing to the console, accessing a database, or changing a global variable. Impure functions are useful but are often error-prone and hard to test due to their side effects.
Anonymous Functions
Anonymous functions are functions without an assigned name. They are used to perform one-off tasks.
lambda x: x * x
Anonymous functions are also called lambda expressions. They're covered alongside map(), filter(), and reduce() in the higher-order functions guide.
Higher-Order Functions
Higher-order functions take in other functions as input or return other functions. Popular higher-order functions include map(), filter(), and reduce().
Closures
A closure is a function capable of capturing variables from where it was created. Closures are functions with internal state, and they're created by higher-order functions.
Recursive Functions
A recursive function is a function that can call itself. It has a base case, which serves as its termination point. Recursion is often an alternative to iteration.
The recursion guide covers base cases, call stacks, and practical examples.
Curried Functions
A curried function is a function whose inputs can be partially applied. Curried functions are a form of closures. Through this partial application, new functions can be created.
See currying in Python for the distinction between currying and functools.partial().
Generator Functions
Generators are functions that can pause their execution after being called. If they are called again, they resume from where they stopped previously.
def infCount():
i = 0
while True:
yield i
i += 1
# Usage
inf = infCount()
next(inf) # 0
next(inf) # 1
next(inf) # 2
Coroutine Functions
Coroutines are functions capable of multitasking cooperatively. A function working cooperatively can pause its execution and hand control off to another function when it is idle or performing a blocking task.
Thanks to the async and await keywords introduced in PEP 492, they have become common and intuitive.
import asyncio
import time
async def chill(label: str, n: int):
print(f"{label}: Chilling for {n} seconds")
await asyncio.sleep(n)
print(f"Done chilling for {label}")
async def main():
task1 = asyncio.create_task(chill("A", 2))
task2 = asyncio.create_task(chill("B", 5))
task3 = asyncio.create_task(chill("C", 3))
starttime = time.perf_counter()
await task1
await task2
await task3
endtime = time.perf_counter()
print(f"Task finished in {endtime - starttime}")
asyncio.run(main())
Methods
An object is a collection of related data and functions. Functions in an object are called methods. Rather than manipulating the data directly, methods are used. This is known as encapsulation.
The Python classes and objects guide covers methods, constructors, instances, and encapsulation in detail.
Decorators
Decorators are functions which add extra functionality to previously existing functions. They are similar to closures but have a special syntax. The Python decorators guide covers decorator functions, @ syntax, *args, **kwargs, and decorators with arguments.
Frequently Asked Questions
What are the main types of functions in Python?
Common categories include regular functions, lambda functions, pure and impure functions, higher-order functions, closures, recursive functions, generators, coroutines, and methods.
What is the difference between a function and a method in Python?
A function is defined independently. A method is a function defined on a class and bound to a class or instance when accessed.
What is a pure function in Python?
A pure function returns the same output for the same input and has no side effects, such as changing external state, printing, or making network requests.
What is a higher-order function in Python?
A higher-order function accepts another function as an argument, returns a function, or both. map, filter, and functools.reduce are common examples.
What is the difference between a closure and a recursive function?
A closure remembers values from an enclosing scope. A recursive function calls itself until it reaches a base case.
