Registry / database / pymemcache

pymemcache

JSON →
library4.0.0pypypi✓ verified 26d ago

pymemcache is a comprehensive, fast, pure-Python client for memcached. It fully implements the memcached text protocol and supports connections over UNIX sockets, TCP (IPv4 or IPv6), and configurable timeouts. It is currently at version 4.0.0 and maintains an active release cadence.

pip install pymemcache
INSTALL
IMPORT
SIG · PYMEMCACHE
P
pymemcache
databasepythonv4.0.0
Install
1.6s avg
Import
68ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.070s · 18.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.066s · 19MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Client
from pymemcache.client.base import Client
from memcache import Client
Common mistake when migrating from the older 'python-memcached' library.
HashClient
from pymemcache.client.hash import HashClient
from pymemcache import HashClient (prior to v3.3.0)
While 'HashClient' can be imported directly from 'pymemcache' since v3.3.0, the explicit path 'pymemcache.client.hash' is also widely used and clear.

This quickstart demonstrates how to connect to a memcached server using `pymemcache.Client`, set a key-value pair with an expiration, and retrieve it. Note that `pymemcache` returns values as bytes, requiring explicit decoding for string values.

import os from pymemcache.client.base import Client MEMCACHED_HOST = os.environ.get('MEMCACHED_HOST', '127.0.0.1') MEMCACHED_PORT = int(os.environ.get('MEMCACHED_PORT', '11211')) # It's highly recommended to set timeouts to prevent blocking indefinitely client = Client((MEMCACHED_HOST, MEMCACHED_PORT), connect_timeout=1, timeout=0.5) key = 'my_test_key' value = 'my_test_value' # Set a key-value pair success = client.set(key, value, expire=60) # expire in 60 seconds print(f"Set '{key}': {value} - Success: {success}") # Get the value back retrieved_value = client.get(key) if retrieved_value: # pymemcache returns bytes, decode to string if necessary print(f"Retrieved '{key}': {retrieved_value.decode('utf-8')}") else: print(f"Key '{key}' not found or expired.") client.close()
Debug
Known issues
breakingVersion 4.0.0 dropped official support for Python 2.7, 3.4, and 3.5. Ensure your project uses Python 3.7 or newer before upgrading to v4.0.0.
fix
Upgrade to Python 3.7+ or pin pymemcache to <4.0.0.
affects: >=4.0.0
gotcha`get()` and `get_many()` methods return values as `bytes`, not `str`. You must explicitly decode the retrieved bytes if you expect a string.
fix
After retrieval, use `.decode('utf-8')` (or appropriate encoding) on the returned value: `value.decode('utf-8')`.
affects: All versions
gotchaMemcached keys must adhere to the ASCII protocol and cannot contain spaces, newlines, carriage returns, or null characters by default. Using non-ASCII or illegal characters will raise `MemcacheIllegalInputError`.
fix
Ensure keys are ASCII compliant. For unicode keys, instantiate the client with `allow_unicode_keys=True` and ensure consistent encoding (e.g., UTF-8) across clients.
affects: All versions
breakingThe `expire` argument (previously `time` in `python-memcached`) for set operations now strictly expects an integer representing seconds. Floating-point values are no longer accepted.
fix
Convert any float `expire` values to `int`.
affects: All versions
breakingIn version 3.0.0, the serialization API was refactored. Instead of separate `serializer` and `deserializer` arguments, client objects now expect a single `serde` object that implements `serialize` and `deserialize` methods.
fix
Update custom serialization logic to use the `serde` object pattern. For example: `client = Client(..., serde=MyCustomSerde())`.
affects: >=3.0.0
gotchaFailing to set `connect_timeout` and `timeout` in client constructors can cause your application to block indefinitely if the memcached server is slow or unavailable. This is crucial for production environments.
fix
Always provide explicit `connect_timeout` and `timeout` values (e.g., `Client(..., connect_timeout=1, timeout=0.5)`).
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pymemcache'
The 'pymemcache' library has not been installed in your Python environment or is not accessible within the current environment.
fix
Install the library using pip: `pip install pymemcache`
ConnectionRefusedError: [Errno 111] Connection refused
The pymemcache client attempted to connect to a Memcached server, but the connection was actively refused, usually because the Memcached server is not running, is not listening on the specified host/port, or a firewall is blocking the connection.
fix
Ensure the Memcached server is running and accessible from the machine where your Python application is executing, and that the client is configured with the correct host and port (e.g., `Client('127.0.0.1:11211')`).
AttributeError: module 'memcache' has no attribute 'Client'
This error often occurs when developers confuse `pymemcache` with the older `python-memcached` library and attempt to import `Client` from the incorrect top-level 'memcache' module instead of `pymemcache.client.base`.
fix
Change the import statement from `import memcache` to `from pymemcache.client.base import Client`.
pymemcache.exceptions.MemcacheError: All servers seem to be down right now.
The pymemcache client, particularly `HashClient` or `PooledClient` which manage multiple servers, was unable to establish a connection with any of the configured Memcached servers.
fix
Verify that all Memcached servers specified in the client configuration are running and reachable. For `Client` instances, this typically means the single configured server is down. Consider using `RetryingClient` or `ignore_exc=True` for graceful degradation, but always investigate server availability.
pymemcache.get() returns bytes (e.g., b'some_value') instead of string (e.g., 'some_value')
By default, `pymemcache` stores and retrieves values as bytes, which is the native format for memcached. If you expect string values, you need to explicitly decode them or provide a deserializer.
fix
Decode the retrieved bytes to a string (e.g., `client.get('key').decode('utf-8')`) or configure the client with a `serde` object or separate `serializer` and `deserializer` functions upon initialization. For example: `from pymemcache.serde import python_memcache_serializer, python_memcache_deserializer; client = Client(('localhost', 11211), serializer=python_memcache_serializer, deserializer=python_memcache_deserializer)`.
Upgrade
Version history
4.0.0latest on PyPI · released Oct 17, 2022
Audit
Dependencies
memcachedrequiredRequires a running memcached server to function.
Agent activity
7 hits · last 30 days
node
6
Resources
pymemcache — pip install pymemcache · libregistry