kioku-space

As a personal memory space.

Building a Discord Chatbot with Python (1) - An Introduction

In this guide, we’ll create a “chatbot”, a program that automatically responds to messages in a chat using Python.

Developing a chatbot is a rewarding next step for beginners who have just completed their basic tutorials or courses.
Over the course of several articles, we’ll add various features to our chatbot, making it more versatile and interactive.

Throughout this series, we aim to add the following functions to our chatbot:

Implementing TTL Cache in Python (3)

In this article, we will extend our previously implemented TTL cache decorator with a toggle feature for enabling and disabling the cache.

Here are the specifications for the new cache toggle feature:

  1. Functions decorated with lru_cache will have an additional use_cache argument, allowing one to toggle the cache functionality.
  2. If use_cache is set to False, the function will execute without using the cache,
    but its result will still be stored in the cache.
  3. If toggled back to use_cache=True, the cached content will be utilized.

There are various possible ways to implement this feature. Here’s how I approached it:

Implementing TTL Cache in Python (2)

Continuing from our last article, we’ll delve deeper into implementing a cache with Time-to-Live (TTL).
Let’s quickly recap what we covered previously.

  1. We learned how to equip functions with cache capabilities using lru_cache.
  2. We implemented the get_ttl_hash function, which updates return values at specified intervals.
  3. We were able to give functions TTL caching by:
    1. Enhancing them with the caching functionality of lru_cache.
    2. Adding a dummy argument.
    3. Inputting the return value of get_ttl_hash to the dummy argument.

Our goal in this article is to create a decorator that automates this process.

Implementing TTL Cache in Python (1)

In this article, we’ll discuss how to implement a caching mechanism in Python that has a Time-To-Live (TTL).
This cache can be useful in scenarios like:

  • Functions that connect to the internet to fetch data, but the data remains constant over a period.
    (e.g., weather forecast data)
  • Functions that are executed frequently but don’t require real-time data.

First, let’s see how to add caching to a Python function.