Skip to content

hset and hmset unexpectedly mutates the list passed to items if key+value or mapping is also used #3052

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
yvan-the-barbarian opened this issue Nov 23, 2023 · 0 comments · Fixed by #3103

Comments

@yvan-the-barbarian
Copy link

yvan-the-barbarian commented Nov 23, 2023

Version: redis-py 5.0.1 (Any Redis version)

Platform: Any platform

Description:
If the items parameter of the hset or hmset method is used in conjunction with the key and value, or with the mapping parameters, the list passed to the items parameter is unexpectedly mutated.

For example, using the code below:

from redis.client import Redis

redis = Redis.from_url('redis://127.0.0.1')

items = [
    'one', b'1',
    'two', b'2',
    'three', b'3',
]

redis.hset('test', items=items, key='four', value=b'4')

print(items)

redis.close()

After the method call, items is expectantly updated to ['one', b'1', 'two', b'2', 'three', b'3', 'four', b'4'].

Calling the method should, in principle, not change any of the objects sent as parameters.

As a suggestion, the code could be changed to:

        if key is None and not mapping and not items:
            raise DataError("'hset' with no key value pairs")

        sources = []
        
        if items:
            sources.append(items)
        
        if key is not None:
            sources.append((key, value))
        
        if mapping:
            sources.append(value for entry in mapping.items() for value in entry)

        return self.execute_command("HSET", name, *chain(*sources))

This would have the added benefit of allowing items to be any kind of Iterable object and not just lists.

(In the same vein of ideas, the mapping parameter could be changed to typing.Mapping to allow any mapping instead of just dicts)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant