Advanced Concepts for Self-taught Devs: Intro to Memoization in Python

Advanced Programming Concepts for Self-taught Beginners

Image for post
Image for post
Photo by Sean Lim on Unsplash

So what is memoization?

Memoization (from the root word memo or memorandum) is a way of optimizing your code to speed it up. Specifically, it’s a technique of caching results from a function.

Let’s walk through what this might look like in theory.

Say we have some function f that does some costly calculation. We want to write a function g that memoizes the results. So that g(x) checks to see if we already have f(x) stored first and only if it doesn’t then execute f(x), store the result for the future, and then return the result.

  1. If we do, it immediately returns the results.
  2. If we don’t, it executes f(x)
  3. It then caches the result for future use
  4. Then, it returns the result.

cache = {‘x’ : ‘y’}

where x is the input to our function and y is the output value being stored

So what is a decorator?

A decorator is the Python implementation of a software design pattern that enables functionality for a function to alter another function, method, or class dynamically. A simple way to think about it is a decorator is a function that takes another function and extends its behavior. Here’s where it gets a bit confusing- the decorator itself isn’t the software design pattern that’s important. The decorator is a nice way to do what we need to do, enabling one function to alter another. The thing we’re actually doing is a Closure.

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Founder/CEO of Achilleion.com, Developer, Cyber Security Eng, Privacy Advocate, Python & Golang. Trying to build in public. I write about startups and security.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store