Skip to main content
# LRU Expiring Cache

[![Build Status](https://travis-ci.org/vpaliy/lru-cache.svg?branch=master)](https://travis-ci.org/vpaliy/lru-cache)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![codecov](https://codecov.io/gh/vpaliy/lru-cache/branch/master/graph/badge.svg)](https://codecov.io/gh/vpaliy/lru-cache)

This repository contains a dictionary-like data structure, supporting LRU caching semantics and data expiration mechanism. You can add a new record to the cache and assign an expiration time for that record. Records are not required to have the same "life span": you can mix them up, and it will still work.

### How does it work?
LRU cache uses a daemon thread - AKA cache cleaner - to silently clean up expired items in the background. The daemon thread receives proxied objects from a shared queue, picks up the one with the shortest life span, and uses a condition variable to wait until the record expires.

### Install

`pip install lru-expiring-cache`

or:

```
$ git clone https://github.com/vpaliy/lru-expiring-cache.git
$ cd lru-expiring-cache/
```


### Usage

```python
import time
from lru import LruCache

# every record will expire in 5 seconds unless otherwise specified
cache = LruCache(maxsize=10, expires=5)
cache['foo'] = 'bar'

print(cache['foo']) # prints 'bar'

# sleep for 5 minutes
time.sleep(5)

print(cache['foo']) # KeyError

# adding a new item that expires in 10 seconds
cache.add(key='foo', value='bar', expires=10)

# deleting
del cache['foo']
```

To make the LRU cache thread-safe, just pass `concurrent=True` when constructing a new instance:

```python
from lru import LruCache

cache = LruCache(maxsize=10, concurrent=True)
```

Note: LRU cache extends the `MutableMapping` interface from the standard library; therefore it supports all methods inherent to the standard mapping types in Python.

Additionally, you can use cache decorators:

- `lru_cache(maxsize, expires)`
- `lazy_cache(maxsize, expires)`

Both are memoization decorators that support data expiration. The difference is that `lru_cache` uses `LruCache` (obviously) under the hood, and `lazy_cache` uses the native `dict`.

For example, using `lazy_cache` is super easy:

```python
import time
from lru import lazy_cache

# each new item will expire in 10 seconds
@lazy_cache(maxsize=10, expires=10)
def function(first, second, third):
# simulate performing a computationaly expensive task
time.sleep(10)
return first + second + third

function(10, 10, 10) # sleeps for 10 seconds and returns 30
function(10, 10, 10) # returns 30 instantaneously

time.sleep(10) # wait until expires

function(10, 10, 10) # sleeps for 10 seconds because all cached results have expired

```

Which one to use?

If your function requires the functionality of LRU cache (removing the least recently used records to give room to the new ones), then use `lru_cache`; otherwise if you just need an expiring caching mechaniism, use `lazy_cache`. Note that `lazy_cache` clears the entire cache when the number of records have reached `maxsize`.


## License
```
MIT License

Copyright (c) 2019 Vasyl Paliy

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```


Release files for lru-expiring-cache 1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lru-expiring-cache 1.1
File Size Uploaded
lru-expiring-cache-1.1.tar.gz 10.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for lru-expiring-cache 1.1
File Interpreter ABI Platform
lru_expiring_cache-1.1-py2.py3-none-any.whl Python 2, Python 3 none any Details

Total release size: 22.8 kB

Release files / lru-expiring-cache-1.1.tar.gz

Download URL lru-expiring-cache-1.1.tar.gz
Size 10.5 kB
Tags Source
SHA-256 checksum
How to use checksums
b5e4899e3cfe4d34dbe2b9abc50fddeed2c223ba6bc7b3a996dd3e4bb39d6236
BLAKE2b-256 checksum
How to use checksums
9dbde649e2174313c347ebc6949a754b358e9703f1f1ca46ef8173557cf81aa5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.4.2 requests/2.19.1 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.28.1 CPython/2.7.15rc1

Release files / lru_expiring_cache-1.1-py2.py3-none-any.whl

Download URL lru_expiring_cache-1.1-py2.py3-none-any.whl
Size 12.2 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
cefd4354b05f2af2ffc672c3b0e0082ebe50e19bd9e6e43f9e118a0fa3dadfb0
BLAKE2b-256 checksum
How to use checksums
50de04bcc402d35248922d1e794ed02ee1094665e5aa2bb910ffa45bbebf3b91
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.4.2 requests/2.19.1 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.28.1 CPython/2.7.15rc1

Release history Release notifications | RSS feed

This release

1.1 This release

2 release files

1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page