Skip to content

Commit 393a2b5

Browse files
committed
docs(README): add guidance for handling un-serializable arguments in RedisFuncCache
- Provide two methods to work around un-serializable arguments: 1. Splitting function into two parts 2. Using exclude_keyword_args or exclude_positional_args - Include example with database query and ConnectionPool argument - Emphasize correct usage of exclude parameters
1 parent ade9ae4 commit 393a2b5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,37 @@ def some_func(*args, **kwargs):
721721
> The purpose of the hash algorithm is to ensure the isolation of cached return values for different function invocations.
722722
> Therefore, you can generate unique key names using any method, not just hashes.
723723
724+
### Working with Un-Serializable Arguments
725+
726+
As mentioned in the documentation, the [`RedisFuncCache`][] class does not support functions with un-serializable arguments.
727+
However, you can work around this issue by:
728+
729+
- Splitting the function into two parts: one with fully serializable arguments (apply the cache decorator to this part), and another that may contain un-serializable arguments (this part calls the first one).
730+
731+
- Using `exclude_keyword_args` or `exclude_positional_args` to exclude un-serializable arguments from key and hash calculations.
732+
733+
This approach is particularly useful for functions such as a database query.
734+
735+
For example, the `pool` argument in the following function is not serializable:
736+
737+
```python
738+
def get_book(pool: ConnectionPool, book_id: int):
739+
connection = pool.get_connection()
740+
return connection.execute("SELECT * FROM books WHERE book_id = %s", book_id)
741+
```
742+
743+
However, we can exclude the `pool` argument from the key and hash calculations, so the function can be cached:
744+
745+
```python
746+
@cache(exclude_keyword_args=["pool"])
747+
def get_book(pool: ConnectionPool, book_id: int):
748+
...
749+
```
750+
751+
Important:
752+
- When using the `exclude_keyword_args` parameter, ensure that the argument is passed using keyword way.
753+
- When using the `exclude_positional_args` parameter, ensure that the argument is passed using positional way.
754+
724755
## Known Issues
725756
726757
- Cannot decorate a function that has an argument not serializable by [`pickle`][] or other serialization libraries.

0 commit comments

Comments
 (0)