Functional-Programming

2025

Decorators in Python

Python Decorators

Decorators are a way we can use higher order functions to modify other functions. Typically they are used to wrap a function with another function.


def hello(name="Ian"):
    def greeting(func):
        def wrapper(*args, **kwargs):
            print("A man is sitting at the bar, you go up and greet him.")

            if name == "Ian":
                print("My name is Ian, what's yours?")
            else:
                print(f"My name is {name}, what's yours?")

            print("The man glances your way momentarily, then moves to the other end of the bar.")
            result = func(*args, **kwargs)
            return result
        return wrapper
    return greeting

@hello("Alice")
def bar_talk():
    print("You start a conversation about the weather with the bartender instead.")

@hello()
def another_chat():
    print("You shrug your shoulders and ask the bartender about the local sports team.")


print("=== First Interaction ===")
bar_talk()

print("\n=== Second Interaction ===")
another_chat()

In the example above, you would get the following print out:

Read more →

Pure Functions

Pure Functions

Pure functions are functions that return the same result every time, assuming they receive the same inputs. This is made possible by writing the function to be self-contained, meaning it doesn’t rely on variables outside it’s local scope.

Pure functions do not change the external state of the program. They are great for keeping clean code that is easy to debug, but you can’t write an entire program of pure functions, because it wouldn’t actually do anything.

Read more →