Dragonfly

Memcached set in Python (Detailed Guide w/ Code Examples)

In this guide, we will learn about use cases of the set command of Memcached with hands-on code examples in Python.

July 18, 2025

Redis vs. Memcached: 7 Key Differences and How to Choose

Use Case(s)

The set command in Memcached is used to store a value on the server with an associated key.

Common use cases include:

  • Storing session information such as user preferences and shopping cart details.
  • Caching database query results or frequently accessed static data.

Code Examples

Here are a couple of examples using the pymemcache client library for Python.

Example 1: The Basic 'set' Operation

from pymemcache.client.base import Client

client = Client('localhost')
client.set('key', 'value')
result = client.get('some_key')

In this example, we connect to a Memcached server running locally, set a key-value pair, and then read the key.

Example 2: Setting Multiple Keys

from pymemcache.client.base import Client

client = Client('localhost')
client.set_multi({'key1': 'value1', 'key2': 'value2'})

In this second example, we use the set_multi method to set multiple key-value pairs at once. Note that this method is provided by the pymemcache library, instead of a native command provided by Memcached.

Best Practices

  • It's important to remember that Memcached is not persistent storage; it's a caching solution. Ensure that any data stored in Memcached is also stored permanently elsewhere.
  • Keep your keys as descriptive as possible, which helps with debugging when necessary.
  • Avoid storing large objects in Memcached. The maximum size of a value you can store is 1MB, by default.

Common Mistakes

  • A common mistake is ignoring the return value of the set command. It returns STORED or ERROR, which can be useful for error handling.
  • Not understanding that Memcached evicts older data as it runs out of memory by default. If your application depends on certain data always being in the cache, you might run into unexpected behavior.

FAQs

1. Can I store Python objects in Memcached?

Yes, Memcached clients usually provide serialization and deserialization mechanisms, so you can store complex Python objects.

2. What happens when Memcached runs out of memory?

When Memcached runs out of memory, by default, it starts evicting older (LRU) items to make space for new ones.

Was this content helpful?

Help us improve by giving us your feedback.

Dragonfly Wings

Stay up to date on all things Dragonfly

Join our community for unparalleled support and insights

Join

Switch & save up to 80%

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost