Skip to content

glide_shared

ALL_CHANNELS = None module-attribute

Constant representing 'unsubscribe from all channels'. Pass this to unsubscribe() to unsubscribe from all channels.

ALL_PATTERNS = None module-attribute

Constant representing 'unsubscribe from all patterns'. Pass this to punsubscribe() to unsubscribe from all patterns.

ALL_SHARDED_CHANNELS = None module-attribute

Constant representing 'unsubscribe from all sharded channels'. Pass this to sunsubscribe() to unsubscribe from all sharded channels.

Batch

Bases: BaseBatch

Batch implementation for standalone GlideClient. Batches allow the execution of a group of commands in a single step.

Batch Response

An array of command responses is returned by the client exec command, in the order they were given. Each element in the array represents a command given to the Batch. The response for each command depends on the executed Valkey command. Specific response types are documented alongside each method.

Parameters:

Name Type Description Default
is_atomic bool

Determines whether the batch is atomic or non-atomic. If True, the batch will be executed as an atomic transaction. If False, the batch will be executed as a non-atomic pipeline.

required

See Valkey Transactions (Atomic Batches) and Valkey Pipelines (Non-Atomic Batches) for details.

Note for Standalone Mode (Cluster Mode Disabled): Standalone Batches are executed on the primary node.

Examples:

Atomic Batch - Transaction:
>>> transaction = Batch(is_atomic=True)  # Atomic (Transaction)
>>> transaction.set("key", "value")
>>> transaction.get("key")
>>> result = await client.exec(transaction, false)
>>> print(result)
[OK, b"value"]
Non-Atomic Batch - Pipeline:
>>> pipeline = Batch(is_atomic=False)  # Non-Atomic (Pipeline)
>>> pipeline.set("key1", "value1")
>>> pipeline.set("key2", "value2")
>>> pipeline.get("key1")
>>> pipeline.get("key2")
>>> result = await client.exec(pipeline, false)
>>> print(result)
[OK, OK, b"value1", b"value2"]
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
class Batch(BaseBatch):
    """
    Batch implementation for standalone GlideClient. Batches allow the execution of a group
    of commands in a single step.

    Batch Response:
        An ``array`` of command responses is returned by the client ``exec`` command,
        in the order they were given. Each element in the array represents a command given to the Batch.
        The response for each command depends on the executed Valkey command.
        Specific response types are documented alongside each method.

    Args:
        is_atomic (bool): Determines whether the batch is atomic or non-atomic. If ``True``,
            the batch will be executed as an atomic transaction. If ``False``,
            the batch will be executed as a non-atomic pipeline.

    See [Valkey Transactions (Atomic Batches)](https://valkey.io/topics/transactions/) and [Valkey Pipelines (Non-Atomic Batches)](https://valkey.io/topics/pipelining/) for details.

    Note for Standalone Mode (Cluster Mode Disabled):
        Standalone Batches are executed on the primary node.

    Examples:
        ### Atomic Batch - Transaction:
        >>> transaction = Batch(is_atomic=True)  # Atomic (Transaction)
        >>> transaction.set("key", "value")
        >>> transaction.get("key")
        >>> result = await client.exec(transaction, false)
        >>> print(result)
        [OK, b"value"]

        #### Non-Atomic Batch - Pipeline:
        >>> pipeline = Batch(is_atomic=False)  # Non-Atomic (Pipeline)
        >>> pipeline.set("key1", "value1")
        >>> pipeline.set("key2", "value2")
        >>> pipeline.get("key1")
        >>> pipeline.get("key2")
        >>> result = await client.exec(pipeline, false)
        >>> print(result)
        [OK, OK, b"value1", b"value2"]

    """

    def select(self, index: int) -> "Batch":
        """
        Change the currently selected database.

        See [valkey.io](https://valkey.io/commands/select/) for details.

        Args:
            index (int): The index of the database to select.

        Command response:
            A simple OK response.
        """
        return self.append_command(RequestType.Select, [str(index)])

    def copy(
        self,
        source: TEncodable,
        destination: TEncodable,
        destinationDB: Optional[int] = None,
        replace: Optional[bool] = None,
    ) -> "Batch":
        """
        Copies the value stored at the `source` to the `destination` key. If `destinationDB`
        is specified, the value will be copied to the database specified by `destinationDB`,
        otherwise the current database will be used. When `replace` is True, removes the
        `destination` key first if it already exists, otherwise performs no action.

        See [valkey.io](https://valkey.io/commands/copy) for more details.

        Args:
            source (TEncodable): The key to the source value.
            destination (TEncodable): The key where the value should be copied to.
            destinationDB (Optional[int]): The alternative logical database index for the destination key.
            replace (Optional[bool]): If the destination key should be removed before copying the value to it.

        Command response:
            bool: True if the source was copied.

            Otherwise, return False.

        Since: Valkey version 6.2.0.
        """
        args = [source, destination]
        if destinationDB is not None:
            args.extend(["DB", str(destinationDB)])
        if replace is not None:
            args.append("REPLACE")

        return self.append_command(RequestType.Copy, args)

    def publish(self, message: TEncodable, channel: TEncodable) -> "Batch":
        """
        Publish a message on pubsub channel.

        See [valkey.io](https://valkey.io/commands/publish) for more details.

        Args:
            message (TEncodable): Message to publish
            channel (TEncodable): Channel to publish the message on.

        Command Respose:
            int: Number of subscriptions in that shard that received the message.

        """
        return self.append_command(RequestType.Publish, [channel, message])

select(index)

Change the currently selected database.

See valkey.io for details.

Parameters:

Name Type Description Default
index int

The index of the database to select.

required
Command response

A simple OK response.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
def select(self, index: int) -> "Batch":
    """
    Change the currently selected database.

    See [valkey.io](https://valkey.io/commands/select/) for details.

    Args:
        index (int): The index of the database to select.

    Command response:
        A simple OK response.
    """
    return self.append_command(RequestType.Select, [str(index)])

copy(source, destination, destinationDB=None, replace=None)

Copies the value stored at the source to the destination key. If destinationDB is specified, the value will be copied to the database specified by destinationDB, otherwise the current database will be used. When replace is True, removes the destination key first if it already exists, otherwise performs no action.

See valkey.io for more details.

Parameters:

Name Type Description Default
source TEncodable

The key to the source value.

required
destination TEncodable

The key where the value should be copied to.

required
destinationDB Optional[int]

The alternative logical database index for the destination key.

None
replace Optional[bool]

If the destination key should be removed before copying the value to it.

None
Command response

bool: True if the source was copied.

Otherwise, return False.

Since: Valkey version 6.2.0.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
def copy(
    self,
    source: TEncodable,
    destination: TEncodable,
    destinationDB: Optional[int] = None,
    replace: Optional[bool] = None,
) -> "Batch":
    """
    Copies the value stored at the `source` to the `destination` key. If `destinationDB`
    is specified, the value will be copied to the database specified by `destinationDB`,
    otherwise the current database will be used. When `replace` is True, removes the
    `destination` key first if it already exists, otherwise performs no action.

    See [valkey.io](https://valkey.io/commands/copy) for more details.

    Args:
        source (TEncodable): The key to the source value.
        destination (TEncodable): The key where the value should be copied to.
        destinationDB (Optional[int]): The alternative logical database index for the destination key.
        replace (Optional[bool]): If the destination key should be removed before copying the value to it.

    Command response:
        bool: True if the source was copied.

        Otherwise, return False.

    Since: Valkey version 6.2.0.
    """
    args = [source, destination]
    if destinationDB is not None:
        args.extend(["DB", str(destinationDB)])
    if replace is not None:
        args.append("REPLACE")

    return self.append_command(RequestType.Copy, args)

publish(message, channel)

Publish a message on pubsub channel.

See valkey.io for more details.

Parameters:

Name Type Description Default
message TEncodable

Message to publish

required
channel TEncodable

Channel to publish the message on.

required
Command Respose

int: Number of subscriptions in that shard that received the message.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
def publish(self, message: TEncodable, channel: TEncodable) -> "Batch":
    """
    Publish a message on pubsub channel.

    See [valkey.io](https://valkey.io/commands/publish) for more details.

    Args:
        message (TEncodable): Message to publish
        channel (TEncodable): Channel to publish the message on.

    Command Respose:
        int: Number of subscriptions in that shard that received the message.

    """
    return self.append_command(RequestType.Publish, [channel, message])

ClusterBatch

Bases: BaseBatch

Batch implementation for cluster GlideClusterClient. Batches allow the execution of a group of commands in a single step.

Batch Response

An array of command responses is returned by the client exec command, in the order they were given. Each element in the array represents a command given to the ClusterBatch. The response for each command depends on the executed Valkey command. Specific response types are documented alongside each method.

Parameters:

Name Type Description Default
is_atomic bool

Determines whether the batch is atomic or non-atomic. If True, the batch will be executed as an atomic transaction. If False, the batch will be executed as a non-atomic pipeline.

required

See Valkey Transactions (Atomic Batches) and Valkey Pipelines (Non-Atomic Batches) for details.

Examples:

Atomic Batch - Transaction in a Cluster:
>>> transaction = ClusterBatch(is_atomic=True)  # Atomic (Transaction)
>>> transaction.set("key", "value")
>>> transaction.get("key")
>>> result = await client.exec(transaction, false)
>>> print(result)
[OK, b"value"]
Non-Atomic Batch - Pipeline in a Cluster:
>>> pipeline = ClusterBatch(is_atomic=False)  # Non-Atomic (Pipeline)
>>> pipeline.set("key1", "value1")
>>> pipeline.set("key2", "value2")
>>> pipeline.get("key1")
>>> pipeline.get("key2")
>>> result = await client.exec(pipeline, false)
>>> print(result)
[OK, OK, b"value1", b"value2"]
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
class ClusterBatch(BaseBatch):
    """
    Batch implementation for cluster GlideClusterClient. Batches allow the execution of a group
    of commands in a single step.

    Batch Response:
        An ``array`` of command responses is returned by the client ``exec`` command,
        in the order they were given. Each element in the array represents a command given to the ClusterBatch.
        The response for each command depends on the executed Valkey command.
        Specific response types are documented alongside each method.

    Args:
        is_atomic (bool): Determines whether the batch is atomic or non-atomic. If ``True``,
            the batch will be executed as an atomic transaction. If ``False``,
            the batch will be executed as a non-atomic pipeline.

    See [Valkey Transactions (Atomic Batches)](https://valkey.io/topics/transactions/) and [Valkey Pipelines (Non-Atomic Batches)](https://valkey.io/topics/pipelining/) for details.

    Examples:
        ### Atomic Batch - Transaction in a Cluster:
        >>> transaction = ClusterBatch(is_atomic=True)  # Atomic (Transaction)
        >>> transaction.set("key", "value")
        >>> transaction.get("key")
        >>> result = await client.exec(transaction, false)
        >>> print(result)
        [OK, b"value"]

        ### Non-Atomic Batch - Pipeline in a Cluster:
        >>> pipeline = ClusterBatch(is_atomic=False)  # Non-Atomic (Pipeline)
        >>> pipeline.set("key1", "value1")
        >>> pipeline.set("key2", "value2")
        >>> pipeline.get("key1")
        >>> pipeline.get("key2")
        >>> result = await client.exec(pipeline, false)
        >>> print(result)
        [OK, OK, b"value1", b"value2"]

    """

    def copy(
        self,
        source: TEncodable,
        destination: TEncodable,
        # TODO next major release the arguments replace and destinationDB must have their order
        # swapped to align with the standalone order.
        # At the moment of the patch release 2.1.1. we can't have a breaking change
        replace: Optional[bool] = None,
        destinationDB: Optional[int] = None,
    ) -> "ClusterBatch":
        """
        Copies the value stored at the `source` to the `destination` key. When `replace` is True,
        removes the `destination` key first if it already exists, otherwise performs no action.

        See [valkey.io](https://valkey.io/commands/copy) for more details.

        Args:
            source (TEncodable): The key to the source value.
            destination (TEncodable): The key where the value should be copied to.
            replace (Optional[bool]): If the destination key should be removed before copying the value to it.
            destinationDB (Optional[int]): The alternative logical database index for the destination key.
        Command response:
            bool: True if the source was copied.

            Otherwise, return False.

        Since: Valkey version 9.0.0.
        """
        args = [source, destination]
        if destinationDB is not None:
            args.extend(["DB", str(destinationDB)])
        if replace is not None:
            args.append("REPLACE")

        return self.append_command(RequestType.Copy, args)

    def publish(
        self, message: str, channel: str, sharded: bool = False
    ) -> "ClusterBatch":
        """
        Publish a message on pubsub channel.
        This command aggregates PUBLISH and SPUBLISH commands functionalities.
        The mode is selected using the 'sharded' parameter

        See [PUBLISH](https://valkey.io/commands/publish) and [SPUBLISH](https://valkey.io/commands/spublish)
        for more details.

        Args:
            message (str): Message to publish
            channel (str): Channel to publish the message on.
            sharded (bool): Use sharded pubsub mode. Available since Valkey version 7.0.

        Returns:
            int: Number of subscriptions in that shard that received the message.
        """
        return self.append_command(
            RequestType.SPublish if sharded else RequestType.Publish, [channel, message]
        )

    def pubsub_shardchannels(
        self, pattern: Optional[TEncodable] = None
    ) -> "ClusterBatch":
        """
        Lists the currently active shard channels.

        See [valkey.io](https://valkey.io/commands/pubsub-shardchannels) for details.

        Args:
            pattern (Optional[TEncodable]): A glob-style pattern to match active shard channels.
                If not provided, all active shard channels are returned.

        Command response:
            List[bytes]: A list of currently active shard channels matching the given pattern.

            If no pattern is specified, all active shard channels are returned.
        """
        command_args = [pattern] if pattern is not None else []
        return self.append_command(RequestType.PubSubShardChannels, command_args)

    def pubsub_shardnumsub(
        self, channels: Optional[List[TEncodable]] = None
    ) -> "ClusterBatch":
        """
        Returns the number of subscribers (exclusive of clients subscribed to patterns) for the specified shard channels.

        Note:
            It is valid to call this command without channels. In this case, it will just return an empty map.

        See [valkey.io](https://valkey.io/commands/pubsub-shardnumsub) for details.

        Args:
            channels (Optional[List[str]]): The list of shard channels to query for the number of subscribers.
                If not provided, returns an empty map.

        Command response:
            Mapping[bytes, int]: A map where keys are the shard channel names and values are the number of subscribers.
        """
        return self.append_command(
            RequestType.PubSubShardNumSub, channels if channels else []
        )

copy(source, destination, replace=None, destinationDB=None)

Copies the value stored at the source to the destination key. When replace is True, removes the destination key first if it already exists, otherwise performs no action.

See valkey.io for more details.

Parameters:

Name Type Description Default
source TEncodable

The key to the source value.

required
destination TEncodable

The key where the value should be copied to.

required
replace Optional[bool]

If the destination key should be removed before copying the value to it.

None
destinationDB Optional[int]

The alternative logical database index for the destination key.

None

Command response: bool: True if the source was copied.

Otherwise, return False.

Since: Valkey version 9.0.0.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
def copy(
    self,
    source: TEncodable,
    destination: TEncodable,
    # TODO next major release the arguments replace and destinationDB must have their order
    # swapped to align with the standalone order.
    # At the moment of the patch release 2.1.1. we can't have a breaking change
    replace: Optional[bool] = None,
    destinationDB: Optional[int] = None,
) -> "ClusterBatch":
    """
    Copies the value stored at the `source` to the `destination` key. When `replace` is True,
    removes the `destination` key first if it already exists, otherwise performs no action.

    See [valkey.io](https://valkey.io/commands/copy) for more details.

    Args:
        source (TEncodable): The key to the source value.
        destination (TEncodable): The key where the value should be copied to.
        replace (Optional[bool]): If the destination key should be removed before copying the value to it.
        destinationDB (Optional[int]): The alternative logical database index for the destination key.
    Command response:
        bool: True if the source was copied.

        Otherwise, return False.

    Since: Valkey version 9.0.0.
    """
    args = [source, destination]
    if destinationDB is not None:
        args.extend(["DB", str(destinationDB)])
    if replace is not None:
        args.append("REPLACE")

    return self.append_command(RequestType.Copy, args)

publish(message, channel, sharded=False)

Publish a message on pubsub channel. This command aggregates PUBLISH and SPUBLISH commands functionalities. The mode is selected using the 'sharded' parameter

See PUBLISH and SPUBLISH for more details.

Parameters:

Name Type Description Default
message str

Message to publish

required
channel str

Channel to publish the message on.

required
sharded bool

Use sharded pubsub mode. Available since Valkey version 7.0.

False

Returns:

Name Type Description
int ClusterBatch

Number of subscriptions in that shard that received the message.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
def publish(
    self, message: str, channel: str, sharded: bool = False
) -> "ClusterBatch":
    """
    Publish a message on pubsub channel.
    This command aggregates PUBLISH and SPUBLISH commands functionalities.
    The mode is selected using the 'sharded' parameter

    See [PUBLISH](https://valkey.io/commands/publish) and [SPUBLISH](https://valkey.io/commands/spublish)
    for more details.

    Args:
        message (str): Message to publish
        channel (str): Channel to publish the message on.
        sharded (bool): Use sharded pubsub mode. Available since Valkey version 7.0.

    Returns:
        int: Number of subscriptions in that shard that received the message.
    """
    return self.append_command(
        RequestType.SPublish if sharded else RequestType.Publish, [channel, message]
    )

pubsub_shardchannels(pattern=None)

Lists the currently active shard channels.

See valkey.io for details.

Parameters:

Name Type Description Default
pattern Optional[TEncodable]

A glob-style pattern to match active shard channels. If not provided, all active shard channels are returned.

None
Command response

List[bytes]: A list of currently active shard channels matching the given pattern.

If no pattern is specified, all active shard channels are returned.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
def pubsub_shardchannels(
    self, pattern: Optional[TEncodable] = None
) -> "ClusterBatch":
    """
    Lists the currently active shard channels.

    See [valkey.io](https://valkey.io/commands/pubsub-shardchannels) for details.

    Args:
        pattern (Optional[TEncodable]): A glob-style pattern to match active shard channels.
            If not provided, all active shard channels are returned.

    Command response:
        List[bytes]: A list of currently active shard channels matching the given pattern.

        If no pattern is specified, all active shard channels are returned.
    """
    command_args = [pattern] if pattern is not None else []
    return self.append_command(RequestType.PubSubShardChannels, command_args)

pubsub_shardnumsub(channels=None)

Returns the number of subscribers (exclusive of clients subscribed to patterns) for the specified shard channels.

Note

It is valid to call this command without channels. In this case, it will just return an empty map.

See valkey.io for details.

Parameters:

Name Type Description Default
channels Optional[List[str]]

The list of shard channels to query for the number of subscribers. If not provided, returns an empty map.

None
Command response

Mapping[bytes, int]: A map where keys are the shard channel names and values are the number of subscribers.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch.py
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
def pubsub_shardnumsub(
    self, channels: Optional[List[TEncodable]] = None
) -> "ClusterBatch":
    """
    Returns the number of subscribers (exclusive of clients subscribed to patterns) for the specified shard channels.

    Note:
        It is valid to call this command without channels. In this case, it will just return an empty map.

    See [valkey.io](https://valkey.io/commands/pubsub-shardnumsub) for details.

    Args:
        channels (Optional[List[str]]): The list of shard channels to query for the number of subscribers.
            If not provided, returns an empty map.

    Command response:
        Mapping[bytes, int]: A map where keys are the shard channel names and values are the number of subscribers.
    """
    return self.append_command(
        RequestType.PubSubShardNumSub, channels if channels else []
    )

BatchOptions

Bases: BaseBatchOptions

Options for a batch request for a standalone client.

Parameters:

Name Type Description Default
timeout Optional[int]

The duration in milliseconds that the client should wait for the batch request to complete. This duration encompasses sending the request, awaiting a response from the server, and any required reconnections or retries. If the specified timeout is exceeded for a pending request, it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.

None
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch_options.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
class BatchOptions(BaseBatchOptions):
    """
    Options for a batch request for a standalone client.

    Args:
        timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
            to complete. This duration encompasses sending the request, awaiting a response from the server,
            and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
            it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.
    """

    def __init__(
        self,
        timeout: Optional[int] = None,
    ):
        """
        Options for a batch request for a standalone client

        Args:
            timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
                to complete. This duration encompasses sending the request, awaiting a response from the server,
                and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
                it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.
        """
        super().__init__(timeout)

BatchRetryStrategy

Defines a retry strategy for cluster batch requests, allowing control over retries in case of server or connection errors.

This strategy determines whether failed commands should be retried, impacting execution order and potential side effects.

Behavior
  • If retry_server_error is True, failed commands with a retriable error (e.g., TRYAGAIN) will be retried.
  • If retry_connection_error is True, batch requests will be retried on connection failures.
Cautions
  • Server Errors: Retrying may cause commands targeting the same slot to be executed out of order.
  • Connection Errors: Retrying may lead to duplicate executions, since the server might have already received and processed the request before the error occurred.
Example Scenario
MGET key {key}:1
SET key "value"

Expected response when keys are empty:

[None, None]
"OK"

However, if the slot is migrating, both commands may return an ASK error and be redirected. Upon ASK redirection, a multi-key command may return a TRYAGAIN error (triggering a retry), while the SET command succeeds immediately. This can result in an unintended reordering of commands if the first command is retried after the slot stabilizes:

["value", None]
"OK"

Note

Currently, retry strategies are supported only for non-atomic batches.

Default

Both retry_server_error and retry_connection_error are set to False.

Parameters:

Name Type Description Default
retry_server_error bool

If True, failed commands with a retriable error (e.g., TRYAGAIN) will be automatically retried.

⚠️ Warning: Enabling this flag may cause commands targeting the same slot to execute out of order.

By default, this is set to False.

False
retry_connection_error bool

If True, batch requests will be retried in case of connection errors.

⚠️ Warning: Retrying after a connection error may lead to duplicate executions, since the server might have already received and processed the request before the error occurred.

By default, this is set to False.

False
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch_options.py
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
class BatchRetryStrategy:
    """
    Defines a retry strategy for cluster batch requests, allowing control over retries in case of
    server or connection errors.

    This strategy determines whether failed commands should be retried, impacting execution order
    and potential side effects.

    Behavior:
        - If `retry_server_error` is `True`, failed commands with a retriable error (e.g.,
          `TRYAGAIN`) will be retried.
        - If `retry_connection_error` is `True`, batch requests will be retried on
          connection failures.

    Cautions:
        - **Server Errors:** Retrying may cause commands targeting the same slot to be executed
          out of order.
        - **Connection Errors:** Retrying may lead to duplicate executions, since the server might
          have already received and processed the request before the error occurred.

    Example Scenario:
        ```
        MGET key {key}:1
        SET key "value"
        ```

        Expected response when keys are empty:
        ```
        [None, None]
        "OK"
        ```

        However, if the slot is migrating, both commands may return an `ASK` error and be
        redirected. Upon `ASK` redirection, a multi-key command may return a `TRYAGAIN`
        error (triggering a retry), while the `SET` command succeeds immediately. This
        can result in an unintended reordering of commands if the first command is retried
        after the slot stabilizes:
        ```
        ["value", None]
        "OK"
        ```

    Note:
        Currently, retry strategies are supported only for non-atomic batches.

    Default:
        Both `retry_server_error` and `retry_connection_error` are set to `False`.

    Args:
        retry_server_error (bool): If `True`, failed commands with a retriable error (e.g., `TRYAGAIN`)
            will be automatically retried.

            ⚠️ **Warning:** Enabling this flag may cause commands targeting the same slot to execute
            out of order.

            By default, this is set to `False`.

        retry_connection_error (bool): If `True`, batch requests will be retried in case of connection errors.

            ⚠️ **Warning:** Retrying after a connection error may lead to duplicate executions, since
            the server might have already received and processed the request before the error occurred.

            By default, this is set to `False`.

    """

    def __init__(
        self,
        retry_server_error: bool = False,
        retry_connection_error: bool = False,
    ):
        """
        Initialize a BatchRetryStrategy.

        Args:
            retry_server_error (bool): If `True`, failed commands with a retriable error (e.g., `TRYAGAIN`)
                will be automatically retried.

                ⚠️ **Warning:** Enabling this flag may cause commands targeting the same slot to execute
                out of order.

                By default, this is set to `False`.

            retry_connection_error (bool): If `True`, batch requests will be retried in case of connection errors.

                ⚠️ **Warning:** Retrying after a connection error may lead to duplicate executions, since
                the server might have already received and processed the request before the error occurred.

                By default, this is set to `False`.

        """
        self.retry_server_error = retry_server_error
        self.retry_connection_error = retry_connection_error

ClusterBatchOptions

Bases: BaseBatchOptions

Options for cluster batch operations.

Parameters:

Name Type Description Default
timeout Optional[int]

The duration in milliseconds that the client should wait for the batch request to complete. This duration encompasses sending the request, awaiting a response from the server, and any required reconnections or retries. If the specified timeout is exceeded for a pending request, it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.

None
route Optional[TSingleNodeRoute]

Configures single-node routing for the batch request. The client will send the batch to the specified node defined by route.

If a redirection error occurs:

  • For Atomic Batches (Transactions), the entire transaction will be redirected.
  • For Non-Atomic Batches (Pipelines), only the commands that encountered redirection errors will be redirected.
None
retry_strategy Optional[BatchRetryStrategy]

⚠️ Please see BatchRetryStrategy and read carefully before enabling these options.

Defines the retry strategy for handling cluster batch request failures.

This strategy determines whether failed commands should be retried, potentially impacting execution order.

  • If retry_server_error is True, retriable errors (e.g., TRYAGAIN) will trigger a retry.
  • If retry_connection_error is True, connection failures will trigger a retry.

Warnings:

  • Retrying server errors may cause commands targeting the same slot to execute out of order.
  • Retrying connection errors may lead to duplicate executions, as it is unclear which commands have already been processed.

Note: Currently, retry strategies are supported only for non-atomic batches.

Recommendation: It is recommended to increase the timeout in timeout when enabling these strategies.

Default: Both retry_server_error and retry_connection_error are set to False.

None
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/batch_options.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
class ClusterBatchOptions(BaseBatchOptions):
    """
    Options for cluster batch operations.

    Args:
        timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
            to complete. This duration encompasses sending the request, awaiting a response from the server,
            and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
            it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.

        route (Optional[TSingleNodeRoute]): Configures single-node routing for the batch request. The client
            will send the batch to the specified node defined by `route`.

            If a redirection error occurs:

            - For Atomic Batches (Transactions), the entire transaction will be redirected.
            - For Non-Atomic Batches (Pipelines), only the commands that encountered redirection errors
              will be redirected.

        retry_strategy (Optional[BatchRetryStrategy]): ⚠️ **Please see `BatchRetryStrategy` and read carefully before enabling these
            options.**

            Defines the retry strategy for handling cluster batch request failures.

            This strategy determines whether failed commands should be retried, potentially impacting
            execution order.

            - If `retry_server_error` is `True`, retriable errors (e.g., TRYAGAIN) will
              trigger a retry.
            - If `retry_connection_error` is `True`, connection failures will trigger a
              retry.

            **Warnings:**

            - Retrying server errors may cause commands targeting the same slot to execute out of
              order.
            - Retrying connection errors may lead to duplicate executions, as it is unclear which
              commands have already been processed.

            **Note:** Currently, retry strategies are supported only for non-atomic batches.

            **Recommendation:** It is recommended to increase the timeout in `timeout`
            when enabling these strategies.

            **Default:** Both `retry_server_error` and `retry_connection_error` are set to
            `False`.

    """

    def __init__(
        self,
        timeout: Optional[int] = None,
        route: Optional[TSingleNodeRoute] = None,
        retry_strategy: Optional[BatchRetryStrategy] = None,
    ):
        """
        Initialize ClusterBatchOptions.

        Args:
            timeout (Optional[int]): The duration in milliseconds that the client should wait for the batch request
                to complete. This duration encompasses sending the request, awaiting a response from the server,
                and any required reconnections or retries. If the specified timeout is exceeded for a pending request,
                it will result in a timeout error. If not explicitly set, the client's default request timeout will be used.

            route (Optional[TSingleNodeRoute]): Configures single-node routing for the batch request. The client
                will send the batch to the specified node defined by `route`.

                If a redirection error occurs:

                - For Atomic Batches (Transactions), the entire transaction will be redirected.
                - For Non-Atomic Batches (Pipelines), only the commands that encountered redirection errors
                will be redirected.

            retry_strategy (Optional[BatchRetryStrategy]): ⚠️ **Please see `BatchRetryStrategy` and read carefully before enabling these
                options.**

                Defines the retry strategy for handling cluster batch request failures.

                This strategy determines whether failed commands should be retried, potentially impacting
                execution order.

                - If `retry_server_error` is `True`, retriable errors (e.g., TRYAGAIN) will
                trigger a retry.
                - If `retry_connection_error` is `True`, connection failures will trigger a
                retry.

                **Warnings:**

                - Retrying server errors may cause commands targeting the same slot to execute out of
                order.
                - Retrying connection errors may lead to duplicate executions, as it is unclear which
                commands have already been processed.

                **Note:** Currently, retry strategies are supported only for non-atomic batches.

                **Recommendation:** It is recommended to increase the timeout in `timeout`
                when enabling these strategies.

                **Default:** Both `retry_server_error` and `retry_connection_error` are set to
                `False`.
        """
        super().__init__(timeout)
        self.retry_strategy = retry_strategy
        self.route = route

BitEncoding

Bases: ABC

Abstract Base Class used to specify a signed or unsigned argument encoding for the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
73
74
75
76
77
78
79
80
81
82
83
84
85
class BitEncoding(ABC):
    """
    Abstract Base Class used to specify a signed or unsigned argument encoding for the `BITFIELD` or `BITFIELD_RO`
    commands.
    """

    @abstractmethod
    def to_arg(self) -> str:
        """
        Returns the encoding as a string argument to be used in the `BITFIELD` or `BITFIELD_RO`
        commands.
        """
        pass

to_arg() abstractmethod

Returns the encoding as a string argument to be used in the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
79
80
81
82
83
84
85
@abstractmethod
def to_arg(self) -> str:
    """
    Returns the encoding as a string argument to be used in the `BITFIELD` or `BITFIELD_RO`
    commands.
    """
    pass

BitFieldGet

Bases: BitFieldSubCommands

Represents the "GET" subcommand for getting a value in the binary representation of the string stored in key.

Attributes:

Name Type Description
encoding BitEncoding

The bit encoding for the subcommand.

offset BitFieldOffset

The offset in the array of bits from which to get the value.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
class BitFieldGet(BitFieldSubCommands):
    """
    Represents the "GET" subcommand for getting a value in the binary representation of the string stored in `key`.

    Attributes:
        encoding (BitEncoding): The bit encoding for the subcommand.
        offset (BitFieldOffset): The offset in the array of bits from which to get the value.
    """

    #: "GET" subcommand string for use in the `BITFIELD` or `BITFIELD_RO` commands.
    GET_COMMAND_STRING = "GET"

    def __init__(self, encoding: BitEncoding, offset: BitFieldOffset):
        self._encoding = encoding
        self._offset = offset

    def to_args(self) -> List[str]:
        return [self.GET_COMMAND_STRING, self._encoding.to_arg(), self._offset.to_arg()]

BitFieldIncrBy

Bases: BitFieldSubCommands

Represents the "INCRBY" subcommand for increasing or decreasing bits in the binary representation of the string stored in key.

Attributes:

Name Type Description
encoding BitEncoding

The bit encoding for the subcommand.

offset BitOffset

The offset in the array of bits where the value will be incremented.

increment int

The value to increment the bits in the binary value by.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
class BitFieldIncrBy(BitFieldSubCommands):
    """
    Represents the "INCRBY" subcommand for increasing or decreasing bits in the binary representation of the
    string stored in `key`.

    Attributes:
        encoding (BitEncoding): The bit encoding for the subcommand.
        offset (BitOffset): The offset in the array of bits where the value will be incremented.
        increment (int): The value to increment the bits in the binary value by.
    """

    #: "INCRBY" subcommand string for use in the `BITFIELD` command.
    INCRBY_COMMAND_STRING = "INCRBY"

    def __init__(self, encoding: BitEncoding, offset: BitFieldOffset, increment: int):
        self._encoding = encoding
        self._offset = offset
        self._increment = increment

    def to_args(self) -> List[str]:
        return [
            self.INCRBY_COMMAND_STRING,
            self._encoding.to_arg(),
            self._offset.to_arg(),
            str(self._increment),
        ]

BitFieldOffset

Bases: ABC

Abstract Base Class representing an offset for an array of bits for the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
124
125
126
127
128
129
130
131
132
133
class BitFieldOffset(ABC):
    """Abstract Base Class representing an offset for an array of bits for the `BITFIELD` or `BITFIELD_RO` commands."""

    @abstractmethod
    def to_arg(self) -> str:
        """
        Returns the offset as a string argument to be used in the `BITFIELD` or `BITFIELD_RO`
        commands.
        """
        pass

to_arg() abstractmethod

Returns the offset as a string argument to be used in the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
127
128
129
130
131
132
133
@abstractmethod
def to_arg(self) -> str:
    """
    Returns the offset as a string argument to be used in the `BITFIELD` or `BITFIELD_RO`
    commands.
    """
    pass

BitFieldOverflow

Bases: BitFieldSubCommands

Represents the "OVERFLOW" subcommand that determines the result of the "SET" or "INCRBY" BITFIELD subcommands when an underflow or overflow occurs.

Attributes:

Name Type Description
overflow_control BitOverflowControl

The desired overflow behavior.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
class BitFieldOverflow(BitFieldSubCommands):
    """
    Represents the "OVERFLOW" subcommand that determines the result of the "SET" or "INCRBY" `BITFIELD` subcommands
    when an underflow or overflow occurs.

    Attributes:
        overflow_control (BitOverflowControl): The desired overflow behavior.
    """

    #: "OVERFLOW" subcommand string for use in the `BITFIELD` command.
    OVERFLOW_COMMAND_STRING = "OVERFLOW"

    def __init__(self, overflow_control: BitOverflowControl):
        self._overflow_control = overflow_control

    def to_args(self) -> List[str]:
        return [self.OVERFLOW_COMMAND_STRING, self._overflow_control.value]

BitFieldSet

Bases: BitFieldSubCommands

Represents the "SET" subcommand for setting bits in the binary representation of the string stored in key.

Parameters:

Name Type Description Default
encoding BitEncoding

The bit encoding for the subcommand.

required
offset BitOffset

The offset in the array of bits where the value will be set.

required
value int

The value to set the bits in the binary value to.

required
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
class BitFieldSet(BitFieldSubCommands):
    """
    Represents the "SET" subcommand for setting bits in the binary representation of the string stored in `key`.

    Args:
        encoding (BitEncoding): The bit encoding for the subcommand.
        offset (BitOffset): The offset in the array of bits where the value will be set.
        value (int): The value to set the bits in the binary value to.
    """

    #: "SET" subcommand string for use in the `BITFIELD` command.
    SET_COMMAND_STRING = "SET"

    def __init__(self, encoding: BitEncoding, offset: BitFieldOffset, value: int):
        self._encoding = encoding
        self._offset = offset
        self._value = value

    def to_args(self) -> List[str]:
        return [
            self.SET_COMMAND_STRING,
            self._encoding.to_arg(),
            self._offset.to_arg(),
            str(self._value),
        ]

BitFieldSubCommands

Bases: ABC

Abstract Base Class representing subcommands for the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
179
180
181
182
183
184
185
186
187
class BitFieldSubCommands(ABC):
    """Abstract Base Class representing subcommands for the `BITFIELD` or `BITFIELD_RO` commands."""

    @abstractmethod
    def to_args(self) -> List[str]:
        """
        Returns the subcommand as a list of string arguments to be used in the `BITFIELD` or `BITFIELD_RO` commands.
        """
        pass

to_args() abstractmethod

Returns the subcommand as a list of string arguments to be used in the BITFIELD or BITFIELD_RO commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
182
183
184
185
186
187
@abstractmethod
def to_args(self) -> List[str]:
    """
    Returns the subcommand as a list of string arguments to be used in the `BITFIELD` or `BITFIELD_RO` commands.
    """
    pass

BitmapIndexType

Bases: Enum

Enumeration specifying if index arguments are BYTE indexes or BIT indexes. Can be specified in OffsetOptions, which is an optional argument to the BITCOUNT command.

Since: Valkey version 7.0.0.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class BitmapIndexType(Enum):
    """
    Enumeration specifying if index arguments are BYTE indexes or BIT indexes. Can be specified in `OffsetOptions`,
    which is an optional argument to the `BITCOUNT` command.

    Since: Valkey version 7.0.0.
    """

    BYTE = "BYTE"
    """
    Specifies that indexes provided to `OffsetOptions` are byte indexes.
    """
    BIT = "BIT"
    """
    Specifies that indexes provided to `OffsetOptions` are bit indexes.
    """

BYTE = 'BYTE' class-attribute instance-attribute

Specifies that indexes provided to OffsetOptions are byte indexes.

BIT = 'BIT' class-attribute instance-attribute

Specifies that indexes provided to OffsetOptions are bit indexes.

BitOffset

Bases: BitFieldOffset

Represents an offset in an array of bits for the BITFIELD or BITFIELD_RO commands. Must be greater than or equal to 0.

For example, if we have the binary 01101001 with offset of 1 for an unsigned encoding of size 4, then the value is 13 from 0(1101)001.

Attributes:

Name Type Description
offset int

The bit index offset in the array of bits.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
class BitOffset(BitFieldOffset):
    """
    Represents an offset in an array of bits for the `BITFIELD` or `BITFIELD_RO` commands. Must be greater than or
    equal to 0.

    For example, if we have the binary `01101001` with offset of 1 for an unsigned encoding of size 4, then the value
    is 13 from `0(1101)001`.

    Attributes:
        offset (int): The bit index offset in the array of bits.
    """

    def __init__(self, offset: int):
        self._offset = str(offset)

    def to_arg(self) -> str:
        return self._offset

BitOffsetMultiplier

Bases: BitFieldOffset

Represents an offset in an array of bits for the BITFIELD or BITFIELD_RO commands. The bit offset index is calculated as the numerical value of the offset multiplied by the encoding value. Must be greater than or equal to 0.

For example, if we have the binary 01101001 with offset multiplier of 1 for an unsigned encoding of size 4, then the value is 9 from 0110(1001).

Attributes:

Name Type Description
offset int

The offset in the array of bits, which will be multiplied by the encoding value to get the final bit index offset.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
class BitOffsetMultiplier(BitFieldOffset):
    """
    Represents an offset in an array of bits for the `BITFIELD` or `BITFIELD_RO` commands. The bit offset index is
    calculated as the numerical value of the offset multiplied by the encoding value. Must be greater than or equal
    to 0.

    For example, if we have the binary 01101001 with offset multiplier of 1 for an unsigned encoding of size 4, then
    the value is 9 from `0110(1001)`.

    Attributes:
        offset (int): The offset in the array of bits, which will be multiplied by the encoding value to get the
            final bit index offset.
    """

    #: Prefix specifying that the offset uses an encoding multiplier.
    OFFSET_MULTIPLIER_PREFIX = "#"

    def __init__(self, offset: int):
        self._offset = f"{self.OFFSET_MULTIPLIER_PREFIX}{str(offset)}"

    def to_arg(self) -> str:
        return self._offset

BitOverflowControl

Bases: Enum

Enumeration specifying bit overflow controls for the BITFIELD command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
class BitOverflowControl(Enum):
    """
    Enumeration specifying bit overflow controls for the `BITFIELD` command.
    """

    WRAP = "WRAP"
    """
    Performs modulo when overflows occur with unsigned encoding. When overflows occur with signed encoding, the value
    restarts at the most negative value. When underflows occur with signed encoding, the value restarts at the most
    positive value.
    """
    SAT = "SAT"
    """
    Underflows remain set to the minimum value, and overflows remain set to the maximum value.
    """
    FAIL = "FAIL"
    """
    Returns `None` when overflows occur.
    """

WRAP = 'WRAP' class-attribute instance-attribute

Performs modulo when overflows occur with unsigned encoding. When overflows occur with signed encoding, the value restarts at the most negative value. When underflows occur with signed encoding, the value restarts at the most positive value.

SAT = 'SAT' class-attribute instance-attribute

Underflows remain set to the minimum value, and overflows remain set to the maximum value.

FAIL = 'FAIL' class-attribute instance-attribute

Returns None when overflows occur.

BitwiseOperation

Bases: Enum

Enumeration defining the bitwise operation to use in the BITOP command. Specifies the bitwise operation to perform between the passed in keys.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
61
62
63
64
65
66
67
68
69
70
class BitwiseOperation(Enum):
    """
    Enumeration defining the bitwise operation to use in the `BITOP` command. Specifies the bitwise operation to
    perform between the passed in keys.
    """

    AND = "AND"
    OR = "OR"
    XOR = "XOR"
    NOT = "NOT"

OffsetOptions

Represents offsets specifying a string interval to analyze in the BITCOUNT command. The offsets are zero-based indexes, with 0 being the first index of the string, 1 being the next index and so on. The offsets can also be negative numbers indicating offsets starting at the end of the string, with -1 being the last index of the string, -2 being the penultimate, and so on.

Attributes:

Name Type Description
start int

The starting offset index.

end Optional[int]

The ending offset index. Optional since Valkey version 8.0.0 and above for the BITCOUNT command. If not provided, it will default to the end of the string.

index_type Optional[BitmapIndexType]

The index offset type. This option can only be specified if you are using Valkey version 7.0.0 or above. Could be either BitmapIndexType.BYTE or BitmapIndexType.BIT. If no index type is provided, the indexes will be assumed to be byte indexes.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class OffsetOptions:
    """
    Represents offsets specifying a string interval to analyze in the `BITCOUNT` command. The offsets are
    zero-based indexes, with `0` being the first index of the string, `1` being the next index and so on.
    The offsets can also be negative numbers indicating offsets starting at the end of the string, with `-1` being
    the last index of the string, `-2` being the penultimate, and so on.

    Attributes:
        start (int): The starting offset index.
        end (Optional[int]): The ending offset index. Optional since Valkey version 8.0.0 and above for the BITCOUNT
            command. If not provided, it will default to the end of the string.
        index_type (Optional[BitmapIndexType]): The index offset type. This option can only be specified if you are
            using Valkey version 7.0.0 or above. Could be either `BitmapIndexType.BYTE` or `BitmapIndexType.BIT`.
            If no index type is provided, the indexes will be assumed to be byte indexes.
    """

    def __init__(
        self,
        start: int,
        end: Optional[int] = None,
        index_type: Optional[BitmapIndexType] = None,
    ):
        self.start = start
        self.end = end
        self.index_type = index_type

    def to_args(self) -> List[str]:
        args = [str(self.start)]
        if self.end:
            args.append(str(self.end))
        if self.index_type is not None:
            args.append(self.index_type.value)

        return args

SignedEncoding

Bases: BitEncoding

Represents a signed argument encoding. Must be less than 65 bits long.

Attributes:

Name Type Description
encoding_length int

The bit size of the encoding.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class SignedEncoding(BitEncoding):
    """
    Represents a signed argument encoding. Must be less than 65 bits long.

    Attributes:
        encoding_length (int): The bit size of the encoding.
    """

    #: Prefix specifying that the encoding is signed.
    SIGNED_ENCODING_PREFIX = "i"

    def __init__(self, encoding_length: int):
        self._encoding = f"{self.SIGNED_ENCODING_PREFIX}{str(encoding_length)}"

    def to_arg(self) -> str:
        return self._encoding

UnsignedEncoding

Bases: BitEncoding

Represents an unsigned argument encoding. Must be less than 64 bits long.

Attributes:

Name Type Description
encoding_length int

The bit size of the encoding.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/bitmap.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class UnsignedEncoding(BitEncoding):
    """
    Represents an unsigned argument encoding. Must be less than 64 bits long.

    Attributes:
        encoding_length (int): The bit size of the encoding.
    """

    #: Prefix specifying that the encoding is unsigned.
    UNSIGNED_ENCODING_PREFIX = "u"

    def __init__(self, encoding_length: int):
        self._encoding = f"{self.UNSIGNED_ENCODING_PREFIX}{str(encoding_length)}"

    def to_arg(self) -> str:
        return self._encoding

Limit

Represents a limit argument for range queries in various commands.

The LIMIT argument is commonly used to specify a subset of results from the matching elements, similar to the LIMIT clause in SQL (e.g., SELECT LIMIT offset, count).

This class can be utilized in multiple commands that support limit options, such as ZRANGE, SORT and others.

Parameters:

Name Type Description Default
offset int

The starting position of the range, zero based.

required
count int

The maximum number of elements to include in the range. A negative count returns all elements from the offset.

required

Examples:

>>> limit = Limit(0, 10)  # Fetch the first 10 elements
>>> limit = Limit(5, -1)  # Fetch all elements starting from the 5th element
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/command_args.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Limit:
    """
    Represents a limit argument for range queries in various commands.

    The `LIMIT` argument is commonly used to specify a subset of results from the matching elements,
    similar to the `LIMIT` clause in SQL (e.g., `SELECT LIMIT offset, count`).

    This class can be utilized in multiple commands that support limit options,
    such as [ZRANGE](https://valkey.io/commands/zrange), [SORT](https://valkey.io/commands/sort/) and others.

    Args:
        offset (int): The starting position of the range, zero based.
        count (int): The maximum number of elements to include in the range.
            A negative count returns all elements from the offset.

    Examples:
        >>> limit = Limit(0, 10)  # Fetch the first 10 elements
        >>> limit = Limit(5, -1)  # Fetch all elements starting from the 5th element
    """

    def __init__(self, offset: int, count: int):
        self.offset = offset
        self.count = count

ListDirection

Bases: Enum

Enumeration representing element popping or adding direction for List commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/command_args.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class ListDirection(Enum):
    """
    Enumeration representing element popping or adding direction for List commands.
    """

    LEFT = "LEFT"
    """
    LEFT: Represents the option that elements should be popped from or added to the left side of a list.
    """

    RIGHT = "RIGHT"
    """
    RIGHT: Represents the option that elements should be popped from or added to the right side of a list.
    """

LEFT = 'LEFT' class-attribute instance-attribute

LEFT: Represents the option that elements should be popped from or added to the left side of a list.

RIGHT = 'RIGHT' class-attribute instance-attribute

RIGHT: Represents the option that elements should be popped from or added to the right side of a list.

ObjectType

Bases: Enum

Enumeration representing the data types supported by the database.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/command_args.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class ObjectType(Enum):
    """
    Enumeration representing the data types supported by the database.
    """

    STRING = "String"
    """
    Represents a string data type.
    """

    LIST = "List"
    """
    Represents a list data type.
    """

    SET = "Set"
    """
    Represents a set data type.
    """

    ZSET = "ZSet"
    """
    Represents a sorted set data type.
    """

    HASH = "Hash"
    """
    Represents a hash data type.
    """

    STREAM = "Stream"
    """
    Represents a stream data type.
    """

STRING = 'String' class-attribute instance-attribute

Represents a string data type.

LIST = 'List' class-attribute instance-attribute

Represents a list data type.

SET = 'Set' class-attribute instance-attribute

Represents a set data type.

ZSET = 'ZSet' class-attribute instance-attribute

Represents a sorted set data type.

HASH = 'Hash' class-attribute instance-attribute

Represents a hash data type.

STREAM = 'Stream' class-attribute instance-attribute

Represents a stream data type.

OrderBy

Bases: Enum

Enumeration representing sorting order options.

This enum is used for the following commands:

- `SORT`: General sorting in ascending or descending order.
- `GEOSEARCH`: Sorting items based on their proximity to a center point.
- `FT.AGGREGATE`: Used in the SortBy clause of the FT.AGGREGATE command.
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/command_args.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class OrderBy(Enum):
    """
    Enumeration representing sorting order options.

    This enum is used for the following commands:

        - `SORT`: General sorting in ascending or descending order.
        - `GEOSEARCH`: Sorting items based on their proximity to a center point.
        - `FT.AGGREGATE`: Used in the SortBy clause of the FT.AGGREGATE command.

    """

    ASC = "ASC"
    """
    ASC: Sort in ascending order.
    """

    DESC = "DESC"
    """
    DESC: Sort in descending order.
    """

ASC = 'ASC' class-attribute instance-attribute

ASC: Sort in ascending order.

DESC = 'DESC' class-attribute instance-attribute

DESC: Sort in descending order.

ConditionalChange

Bases: Enum

A condition to the SET, ZADD and GEOADD commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
27
28
29
30
31
32
33
34
35
36
class ConditionalChange(Enum):
    """
    A condition to the `SET`, `ZADD` and `GEOADD` commands.
    """

    ONLY_IF_EXISTS = "XX"
    """ Only update key / elements that already exist. Equivalent to `XX` in the Valkey API. """

    ONLY_IF_DOES_NOT_EXIST = "NX"
    """ Only set key / add elements that does not already exist. Equivalent to `NX` in the Valkey API. """

ONLY_IF_EXISTS = 'XX' class-attribute instance-attribute

Only update key / elements that already exist. Equivalent to XX in the Valkey API.

ONLY_IF_DOES_NOT_EXIST = 'NX' class-attribute instance-attribute

Only set key / add elements that does not already exist. Equivalent to NX in the Valkey API.

ExpireOptions

Bases: Enum

EXPIRE option: options for setting key expiry.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
class ExpireOptions(Enum):
    """
    EXPIRE option: options for setting key expiry.
    """

    HasNoExpiry = "NX"
    """ Set expiry only when the key has no expiry (Equivalent to "NX" in Valkey). """

    HasExistingExpiry = "XX"
    """ Set expiry only when the key has an existing expiry (Equivalent to "XX" in Valkey). """

    NewExpiryGreaterThanCurrent = "GT"
    """
    Set expiry only when the new expiry is greater than the current one (Equivalent to "GT" in Valkey).
    """

    NewExpiryLessThanCurrent = "LT"
    """
    Set expiry only when the new expiry is less than the current one (Equivalent to "LT" in Valkey).
    """

HasNoExpiry = 'NX' class-attribute instance-attribute

Set expiry only when the key has no expiry (Equivalent to "NX" in Valkey).

HasExistingExpiry = 'XX' class-attribute instance-attribute

Set expiry only when the key has an existing expiry (Equivalent to "XX" in Valkey).

NewExpiryGreaterThanCurrent = 'GT' class-attribute instance-attribute

Set expiry only when the new expiry is greater than the current one (Equivalent to "GT" in Valkey).

NewExpiryLessThanCurrent = 'LT' class-attribute instance-attribute

Set expiry only when the new expiry is less than the current one (Equivalent to "LT" in Valkey).

ExpiryGetEx

GetEx option: Represents the expiry type and value to be executed with "GetEx" command.

Attributes:

Name Type Description
cmd_arg str

The expiry type.

value str

The value for the expiry type.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
class ExpiryGetEx:
    """
    GetEx option: Represents the expiry type and value to be executed with "GetEx" command.

    Attributes:
        cmd_arg (str): The expiry type.
        value (str): The value for the expiry type.
    """

    def __init__(
        self,
        expiry_type: ExpiryTypeGetEx,
        value: Optional[Union[int, datetime, timedelta]],
    ) -> None:
        self.set_expiry_type_and_value(expiry_type, value)

    def set_expiry_type_and_value(
        self,
        expiry_type: ExpiryTypeGetEx,
        value: Optional[Union[int, datetime, timedelta]],
    ):
        """
        Args:
            expiry_type (ExpiryType): The expiry type.
            value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
                determines the type of expiration value:

                    - SEC: Union[int, timedelta]
                    - MILLSEC: Union[int, timedelta]
                    - UNIX_SEC: Union[int, datetime]
                    - UNIX_MILLSEC: Union[int, datetime]
                    - PERSIST: Type[None]
        """
        if not isinstance(value, get_args(expiry_type.value[1])):
            raise ValueError(
                f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
            )
        self.expiry_type = expiry_type
        if self.expiry_type == ExpiryTypeGetEx.SEC:
            self.cmd_arg = "EX"
            if isinstance(value, timedelta):
                value = int(value.total_seconds())
        elif self.expiry_type == ExpiryTypeGetEx.MILLSEC:
            self.cmd_arg = "PX"
            if isinstance(value, timedelta):
                value = int(value.total_seconds() * 1000)
        elif self.expiry_type == ExpiryTypeGetEx.UNIX_SEC:
            self.cmd_arg = "EXAT"
            if isinstance(value, datetime):
                value = int(value.timestamp())
        elif self.expiry_type == ExpiryTypeGetEx.UNIX_MILLSEC:
            self.cmd_arg = "PXAT"
            if isinstance(value, datetime):
                value = int(value.timestamp() * 1000)
        elif self.expiry_type == ExpiryTypeGetEx.PERSIST:
            self.cmd_arg = "PERSIST"
        self.value = str(value) if value else None

    def get_cmd_args(self) -> List[str]:
        return [self.cmd_arg] if self.value is None else [self.cmd_arg, self.value]

set_expiry_type_and_value(expiry_type, value)

Parameters:

Name Type Description Default
expiry_type ExpiryType

The expiry type.

required
value Optional[Union[int, datetime, timedelta]]

The value of the expiration type. The type of expiration determines the type of expiration value:

- SEC: Union[int, timedelta]
- MILLSEC: Union[int, timedelta]
- UNIX_SEC: Union[int, datetime]
- UNIX_MILLSEC: Union[int, datetime]
- PERSIST: Type[None]
required
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def set_expiry_type_and_value(
    self,
    expiry_type: ExpiryTypeGetEx,
    value: Optional[Union[int, datetime, timedelta]],
):
    """
    Args:
        expiry_type (ExpiryType): The expiry type.
        value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
            determines the type of expiration value:

                - SEC: Union[int, timedelta]
                - MILLSEC: Union[int, timedelta]
                - UNIX_SEC: Union[int, datetime]
                - UNIX_MILLSEC: Union[int, datetime]
                - PERSIST: Type[None]
    """
    if not isinstance(value, get_args(expiry_type.value[1])):
        raise ValueError(
            f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
        )
    self.expiry_type = expiry_type
    if self.expiry_type == ExpiryTypeGetEx.SEC:
        self.cmd_arg = "EX"
        if isinstance(value, timedelta):
            value = int(value.total_seconds())
    elif self.expiry_type == ExpiryTypeGetEx.MILLSEC:
        self.cmd_arg = "PX"
        if isinstance(value, timedelta):
            value = int(value.total_seconds() * 1000)
    elif self.expiry_type == ExpiryTypeGetEx.UNIX_SEC:
        self.cmd_arg = "EXAT"
        if isinstance(value, datetime):
            value = int(value.timestamp())
    elif self.expiry_type == ExpiryTypeGetEx.UNIX_MILLSEC:
        self.cmd_arg = "PXAT"
        if isinstance(value, datetime):
            value = int(value.timestamp() * 1000)
    elif self.expiry_type == ExpiryTypeGetEx.PERSIST:
        self.cmd_arg = "PERSIST"
    self.value = str(value) if value else None

ExpirySet

SET option: Represents the expiry type and value to be executed with "SET" command.

Attributes:

Name Type Description
cmd_arg str

The expiry type.

value str

The value for the expiry type.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
class ExpirySet:
    """
    SET option: Represents the expiry type and value to be executed with "SET" command.

    Attributes:
        cmd_arg (str): The expiry type.
        value (str): The value for the expiry type.
    """

    def __init__(
        self,
        expiry_type: ExpiryType,
        value: Optional[Union[int, datetime, timedelta]],
    ) -> None:
        self.set_expiry_type_and_value(expiry_type, value)

    def __eq__(self, other: "object") -> bool:
        if not isinstance(other, ExpirySet):
            return NotImplemented
        return self.expiry_type == other.expiry_type and self.value == other.value

    def set_expiry_type_and_value(
        self, expiry_type: ExpiryType, value: Optional[Union[int, datetime, timedelta]]
    ):
        """
        Args:
            expiry_type (ExpiryType): The expiry type.
            value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
                determines the type of expiration value:

                    - SEC: Union[int, timedelta]
                    - MILLSEC: Union[int, timedelta]
                    - UNIX_SEC: Union[int, datetime]
                    - UNIX_MILLSEC: Union[int, datetime]
                    - KEEP_TTL: Type[None]
        """
        if not isinstance(value, get_args(expiry_type.value[1])):
            raise ValueError(
                f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
            )
        self.expiry_type = expiry_type
        if self.expiry_type == ExpiryType.SEC:
            self.cmd_arg = "EX"
            if isinstance(value, timedelta):
                value = int(value.total_seconds())
        elif self.expiry_type == ExpiryType.MILLSEC:
            self.cmd_arg = "PX"
            if isinstance(value, timedelta):
                value = int(value.total_seconds() * 1000)
        elif self.expiry_type == ExpiryType.UNIX_SEC:
            self.cmd_arg = "EXAT"
            if isinstance(value, datetime):
                value = int(value.timestamp())
        elif self.expiry_type == ExpiryType.UNIX_MILLSEC:
            self.cmd_arg = "PXAT"
            if isinstance(value, datetime):
                value = int(value.timestamp() * 1000)
        elif self.expiry_type == ExpiryType.KEEP_TTL:
            self.cmd_arg = "KEEPTTL"
        self.value = str(value) if value else None

    def get_cmd_args(self) -> List[str]:
        return [self.cmd_arg] if self.value is None else [self.cmd_arg, self.value]

set_expiry_type_and_value(expiry_type, value)

Parameters:

Name Type Description Default
expiry_type ExpiryType

The expiry type.

required
value Optional[Union[int, datetime, timedelta]]

The value of the expiration type. The type of expiration determines the type of expiration value:

- SEC: Union[int, timedelta]
- MILLSEC: Union[int, timedelta]
- UNIX_SEC: Union[int, datetime]
- UNIX_MILLSEC: Union[int, datetime]
- KEEP_TTL: Type[None]
required
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def set_expiry_type_and_value(
    self, expiry_type: ExpiryType, value: Optional[Union[int, datetime, timedelta]]
):
    """
    Args:
        expiry_type (ExpiryType): The expiry type.
        value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
            determines the type of expiration value:

                - SEC: Union[int, timedelta]
                - MILLSEC: Union[int, timedelta]
                - UNIX_SEC: Union[int, datetime]
                - UNIX_MILLSEC: Union[int, datetime]
                - KEEP_TTL: Type[None]
    """
    if not isinstance(value, get_args(expiry_type.value[1])):
        raise ValueError(
            f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
        )
    self.expiry_type = expiry_type
    if self.expiry_type == ExpiryType.SEC:
        self.cmd_arg = "EX"
        if isinstance(value, timedelta):
            value = int(value.total_seconds())
    elif self.expiry_type == ExpiryType.MILLSEC:
        self.cmd_arg = "PX"
        if isinstance(value, timedelta):
            value = int(value.total_seconds() * 1000)
    elif self.expiry_type == ExpiryType.UNIX_SEC:
        self.cmd_arg = "EXAT"
        if isinstance(value, datetime):
            value = int(value.timestamp())
    elif self.expiry_type == ExpiryType.UNIX_MILLSEC:
        self.cmd_arg = "PXAT"
        if isinstance(value, datetime):
            value = int(value.timestamp() * 1000)
    elif self.expiry_type == ExpiryType.KEEP_TTL:
        self.cmd_arg = "KEEPTTL"
    self.value = str(value) if value else None

ExpiryType

Bases: Enum

SET option: The type of the expiry.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class ExpiryType(Enum):
    """
    SET option: The type of the expiry.
    """

    SEC = 0, Union[int, timedelta]
    """
    Set the specified expire time, in seconds. Equivalent to `EX` in the Valkey API.
    """

    MILLSEC = 1, Union[int, timedelta]
    """
    Set the specified expire time, in milliseconds. Equivalent to `PX` in the Valkey API.
    """

    UNIX_SEC = 2, Union[int, datetime]
    """
    Set the specified Unix time at which the key will expire, in seconds. Equivalent to `EXAT` in the Valkey API.
    """

    UNIX_MILLSEC = 3, Union[int, datetime]
    """
    Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to `PXAT` in the Valkey API.
    """

    KEEP_TTL = 4, Type[None]
    """
    Retain the time to live associated with the key. Equivalent to `KEEPTTL` in the Valkey API.
    """

SEC = (0, Union[int, timedelta]) class-attribute instance-attribute

Set the specified expire time, in seconds. Equivalent to EX in the Valkey API.

MILLSEC = (1, Union[int, timedelta]) class-attribute instance-attribute

Set the specified expire time, in milliseconds. Equivalent to PX in the Valkey API.

UNIX_SEC = (2, Union[int, datetime]) class-attribute instance-attribute

Set the specified Unix time at which the key will expire, in seconds. Equivalent to EXAT in the Valkey API.

UNIX_MILLSEC = (3, Union[int, datetime]) class-attribute instance-attribute

Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to PXAT in the Valkey API.

KEEP_TTL = (4, Type[None]) class-attribute instance-attribute

Retain the time to live associated with the key. Equivalent to KEEPTTL in the Valkey API.

ExpiryTypeGetEx

Bases: Enum

GetEx option: The type of the expiry.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
class ExpiryTypeGetEx(Enum):
    """
    GetEx option: The type of the expiry.
    """

    SEC = 0, Union[int, timedelta]
    """ Set the specified expire time, in seconds. Equivalent to `EX` in the Valkey API. """

    MILLSEC = 1, Union[int, timedelta]
    """ Set the specified expire time, in milliseconds. Equivalent to `PX` in the Valkey API. """

    UNIX_SEC = 2, Union[int, datetime]
    """ Set the specified Unix time at which the key will expire, in seconds. Equivalent to `EXAT` in the Valkey API. """

    UNIX_MILLSEC = 3, Union[int, datetime]
    """ Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to `PXAT` in the Valkey API. """

    PERSIST = 4, Type[None]
    """ Remove the time to live associated with the key. Equivalent to `PERSIST` in the Valkey API. """

SEC = (0, Union[int, timedelta]) class-attribute instance-attribute

Set the specified expire time, in seconds. Equivalent to EX in the Valkey API.

MILLSEC = (1, Union[int, timedelta]) class-attribute instance-attribute

Set the specified expire time, in milliseconds. Equivalent to PX in the Valkey API.

UNIX_SEC = (2, Union[int, datetime]) class-attribute instance-attribute

Set the specified Unix time at which the key will expire, in seconds. Equivalent to EXAT in the Valkey API.

UNIX_MILLSEC = (3, Union[int, datetime]) class-attribute instance-attribute

Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to PXAT in the Valkey API.

PERSIST = (4, Type[None]) class-attribute instance-attribute

Remove the time to live associated with the key. Equivalent to PERSIST in the Valkey API.

FlushMode

Bases: Enum

Defines flushing mode for:

FLUSHALL command and FUNCTION FLUSH command.

See FLUSHAL and FUNCTION-FLUSH for details

SYNC was introduced in version 6.2.0.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
class FlushMode(Enum):
    """
    Defines flushing mode for:

    `FLUSHALL` command and `FUNCTION FLUSH` command.

    See [FLUSHAL](https://valkey.io/commands/flushall/) and [FUNCTION-FLUSH](https://valkey.io/commands/function-flush/)
    for details

    SYNC was introduced in version 6.2.0.
    """

    ASYNC = "ASYNC"
    SYNC = "SYNC"

FunctionRestorePolicy

Bases: Enum

Options for the FUNCTION RESTORE command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
class FunctionRestorePolicy(Enum):
    """
    Options for the FUNCTION RESTORE command.
    """

    APPEND = "APPEND"
    """ Appends the restored libraries to the existing libraries and aborts on collision. This is the default policy. """

    FLUSH = "FLUSH"
    """ Deletes all existing libraries before restoring the payload. """

    REPLACE = "REPLACE"
    """
    Appends the restored libraries to the existing libraries, replacing any existing ones in case
    of name collisions. Note that this policy doesn't prevent function name collisions, only libraries.
    """

APPEND = 'APPEND' class-attribute instance-attribute

Appends the restored libraries to the existing libraries and aborts on collision. This is the default policy.

FLUSH = 'FLUSH' class-attribute instance-attribute

Deletes all existing libraries before restoring the payload.

REPLACE = 'REPLACE' class-attribute instance-attribute

Appends the restored libraries to the existing libraries, replacing any existing ones in case of name collisions. Note that this policy doesn't prevent function name collisions, only libraries.

HashFieldConditionalChange

Bases: Enum

Field conditional change options for HSETEX command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
39
40
41
42
43
44
45
46
47
48
class HashFieldConditionalChange(Enum):
    """
    Field conditional change options for HSETEX command.
    """

    ONLY_IF_ALL_EXIST = "FXX"
    """ Only set fields if all of them already exist. Equivalent to `FXX` in the Valkey API. """

    ONLY_IF_NONE_EXIST = "FNX"
    """ Only set fields if none of them already exist. Equivalent to `FNX` in the Valkey API. """

ONLY_IF_ALL_EXIST = 'FXX' class-attribute instance-attribute

Only set fields if all of them already exist. Equivalent to FXX in the Valkey API.

ONLY_IF_NONE_EXIST = 'FNX' class-attribute instance-attribute

Only set fields if none of them already exist. Equivalent to FNX in the Valkey API.

InfoSection

Bases: Enum

INFO option: a specific section of information:

When no parameter is provided, the default option is assumed.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
class InfoSection(Enum):
    """
    INFO option: a specific section of information:

    When no parameter is provided, the default option is assumed.
    """

    SERVER = "server"
    """ General information about the server """

    CLIENTS = "clients"
    """ Client connections section """

    MEMORY = "memory"
    """ Memory consumption related information """

    PERSISTENCE = "persistence"
    """ RDB and AOF related information """

    STATS = "stats"
    """ General statistics """

    REPLICATION = "replication"
    """ Master/replica replication information """

    CPU = "cpu"
    """ CPU consumption statistics """

    COMMAND_STATS = "commandstats"
    """ Valkey command statistics """

    LATENCY_STATS = "latencystats"
    """ Valkey command latency percentile distribution statistics """

    SENTINEL = "sentinel"
    """ Valkey Sentinel section (only applicable to Sentinel instances) """

    CLUSTER = "cluster"
    """ Valkey Cluster section """

    MODULES = "modules"
    """ Modules section """

    KEYSPACE = "keyspace"
    """ Database related statistics """

    ERROR_STATS = "errorstats"
    """ Valkey error statistics """

    ALL = "all"
    """ Return all sections (excluding module generated ones) """

    DEFAULT = "default"
    """ Return only the default set of sections """

    EVERYTHING = "everything"
    """ Includes all and modules """

SERVER = 'server' class-attribute instance-attribute

General information about the server

CLIENTS = 'clients' class-attribute instance-attribute

Client connections section

MEMORY = 'memory' class-attribute instance-attribute

Memory consumption related information

PERSISTENCE = 'persistence' class-attribute instance-attribute

RDB and AOF related information

STATS = 'stats' class-attribute instance-attribute

General statistics

REPLICATION = 'replication' class-attribute instance-attribute

Master/replica replication information

CPU = 'cpu' class-attribute instance-attribute

CPU consumption statistics

COMMAND_STATS = 'commandstats' class-attribute instance-attribute

Valkey command statistics

LATENCY_STATS = 'latencystats' class-attribute instance-attribute

Valkey command latency percentile distribution statistics

SENTINEL = 'sentinel' class-attribute instance-attribute

Valkey Sentinel section (only applicable to Sentinel instances)

CLUSTER = 'cluster' class-attribute instance-attribute

Valkey Cluster section

MODULES = 'modules' class-attribute instance-attribute

Modules section

KEYSPACE = 'keyspace' class-attribute instance-attribute

Database related statistics

ERROR_STATS = 'errorstats' class-attribute instance-attribute

Valkey error statistics

ALL = 'all' class-attribute instance-attribute

Return all sections (excluding module generated ones)

DEFAULT = 'default' class-attribute instance-attribute

Return only the default set of sections

EVERYTHING = 'everything' class-attribute instance-attribute

Includes all and modules

OnlyIfEqual dataclass

Change condition to the SET command, For additional conditonal options see ConditionalChange

  • comparison_value - value to compare to the current value of a key.

If comparison_value is equal to the key, it will overwrite the value of key to the new provided value Equivalent to the IFEQ comparison-value in the Valkey API

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
51
52
53
54
55
56
57
58
59
60
61
62
63
@dataclass
class OnlyIfEqual:
    """
    Change condition to the `SET` command,
    For additional conditonal options see ConditionalChange

    - comparison_value - value to compare to the current value of a key.

    If comparison_value is equal to the key, it will overwrite the value of key to the new provided value
    Equivalent to the IFEQ comparison-value in the Valkey API
    """

    comparison_value: TEncodable

PubSubMsg dataclass

Describes the incoming pubsub message

Attributes:

Name Type Description
message TEncodable

Incoming message.

channel TEncodable

Name of an channel that triggered the message.

pattern Optional[TEncodable]

Pattern that triggered the message.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@dataclass
class PubSubMsg:
    """
    Describes the incoming pubsub message

    Attributes:
        message (TEncodable): Incoming message.
        channel (TEncodable): Name of an channel that triggered the message.
        pattern (Optional[TEncodable]): Pattern that triggered the message.
    """

    message: TEncodable
    channel: TEncodable
    pattern: Optional[TEncodable]

UpdateOptions

Bases: Enum

Options for updating elements of a sorted set key.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/core_options.py
199
200
201
202
203
204
205
206
207
208
class UpdateOptions(Enum):
    """
    Options for updating elements of a sorted set key.
    """

    LESS_THAN = "LT"
    """ Only update existing elements if the new score is less than the current score. """

    GREATER_THAN = "GT"
    """ Only update existing elements if the new score is greater than the current score. """

LESS_THAN = 'LT' class-attribute instance-attribute

Only update existing elements if the new score is less than the current score.

GREATER_THAN = 'GT' class-attribute instance-attribute

Only update existing elements if the new score is greater than the current score.

AggregationType

Bases: Enum

Enumeration representing aggregation types for ZINTERSTORE and ZUNIONSTORE sorted set commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class AggregationType(Enum):
    """
    Enumeration representing aggregation types for `ZINTERSTORE` and `ZUNIONSTORE` sorted set commands.
    """

    SUM = "SUM"
    """
    Represents aggregation by summing the scores of elements across inputs where they exist.
    """
    MIN = "MIN"
    """
    Represents aggregation by selecting the minimum score of an element across inputs where it exists.
    """
    MAX = "MAX"
    """
    Represents aggregation by selecting the maximum score of an element across inputs where it exists.
    """

SUM = 'SUM' class-attribute instance-attribute

Represents aggregation by summing the scores of elements across inputs where they exist.

MIN = 'MIN' class-attribute instance-attribute

Represents aggregation by selecting the minimum score of an element across inputs where it exists.

MAX = 'MAX' class-attribute instance-attribute

Represents aggregation by selecting the maximum score of an element across inputs where it exists.

GeoSearchByBox

Represents search criteria of searching within a specified rectangular area.

Attributes:

Name Type Description
width float

Width of the bounding box.

height float

Height of the bounding box

unit GeoUnit

Unit of the radius. See GeoUnit.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
class GeoSearchByBox:
    """
    Represents search criteria of searching within a specified rectangular area.

    Attributes:
        width (float): Width of the bounding box.
        height (float): Height of the bounding box
        unit (GeoUnit): Unit of the radius. See `GeoUnit`.
    """

    def __init__(self, width: float, height: float, unit: GeoUnit):
        """
        Initialize the search criteria.
        """
        self.width = width
        self.height = height
        self.unit = unit

    def to_args(self) -> List[str]:
        """
        Convert the search criteria to the corresponding part of the command.

        Returns:
            List[str]: List representation of the search criteria.
        """
        return ["BYBOX", str(self.width), str(self.height), self.unit.value]

to_args()

Convert the search criteria to the corresponding part of the command.

Returns:

Type Description
List[str]

List[str]: List representation of the search criteria.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
252
253
254
255
256
257
258
259
def to_args(self) -> List[str]:
    """
    Convert the search criteria to the corresponding part of the command.

    Returns:
        List[str]: List representation of the search criteria.
    """
    return ["BYBOX", str(self.width), str(self.height), self.unit.value]

GeoSearchByRadius

Represents search criteria of searching within a certain radius from a specified point.

Attributes:

Name Type Description
radius float

Radius of the search area.

unit GeoUnit

Unit of the radius. See GeoUnit.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
class GeoSearchByRadius:
    """
    Represents search criteria of searching within a certain radius from a specified point.

    Attributes:
        radius (float): Radius of the search area.
        unit (GeoUnit): Unit of the radius. See `GeoUnit`.
    """

    def __init__(self, radius: float, unit: GeoUnit):
        """
        Initialize the search criteria.
        """
        self.radius = radius
        self.unit = unit

    def to_args(self) -> List[str]:
        """
        Convert the search criteria to the corresponding part of the command.

        Returns:
            List[str]: List representation of the search criteria.
        """
        return ["BYRADIUS", str(self.radius), self.unit.value]

to_args()

Convert the search criteria to the corresponding part of the command.

Returns:

Type Description
List[str]

List[str]: List representation of the search criteria.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
224
225
226
227
228
229
230
231
def to_args(self) -> List[str]:
    """
    Convert the search criteria to the corresponding part of the command.

    Returns:
        List[str]: List representation of the search criteria.
    """
    return ["BYRADIUS", str(self.radius), self.unit.value]

GeoSearchCount

Represents the count option for limiting the number of results in a GeoSearch.

Attributes:

Name Type Description
count int

The maximum number of results to return.

any_option bool

Whether to allow returning as enough matches are found. This means that the results returned may not be the ones closest to the specified point. Default to False.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
class GeoSearchCount:
    """
    Represents the count option for limiting the number of results in a GeoSearch.

    Attributes:
        count (int): The maximum number of results to return.
        any_option (bool): Whether to allow returning as enough matches are found.
            This means that the results returned may not be the ones closest to the specified point. Default to False.
    """

    def __init__(self, count: int, any_option: bool = False):
        """
        Initialize the count option.
        """
        self.count = count
        self.any_option = any_option

    def to_args(self) -> List[str]:
        """
        Convert the count option to the corresponding part of the command.

        Returns:
            List[str]: List representation of the count option.
        """
        if self.any_option:
            return ["COUNT", str(self.count), "ANY"]
        return ["COUNT", str(self.count)]

to_args()

Convert the count option to the corresponding part of the command.

Returns:

Type Description
List[str]

List[str]: List representation of the count option.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
279
280
281
282
283
284
285
286
287
288
def to_args(self) -> List[str]:
    """
    Convert the count option to the corresponding part of the command.

    Returns:
        List[str]: List representation of the count option.
    """
    if self.any_option:
        return ["COUNT", str(self.count), "ANY"]
    return ["COUNT", str(self.count)]

GeospatialData

Represents a geographic position defined by longitude and latitude.

The exact limits, as specified by EPSG:900913 / EPSG:3785 / OSGEO:41001 are the following:

- Valid longitudes are from -180 to 180 degrees.
- Valid latitudes are from -85.05112878 to 85.05112878 degrees.

Attributes:

Name Type Description
longitude float

The longitude coordinate.

latitude float

The latitude coordinate.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
class GeospatialData:
    """
    Represents a geographic position defined by longitude and latitude.

    The exact limits, as specified by EPSG:900913 / EPSG:3785 / OSGEO:41001 are the following:

        - Valid longitudes are from -180 to 180 degrees.
        - Valid latitudes are from -85.05112878 to 85.05112878 degrees.

    Attributes:
        longitude (float): The longitude coordinate.
        latitude (float): The latitude coordinate.
    """

    def __init__(self, longitude: float, latitude: float):
        self.longitude = longitude
        self.latitude = latitude

GeoUnit

Bases: Enum

Enumeration representing distance units options for the GEODIST command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
class GeoUnit(Enum):
    """
    Enumeration representing distance units options for the `GEODIST` command.
    """

    METERS = "m"
    """
    Represents distance in meters.
    """
    KILOMETERS = "km"
    """
    Represents distance in kilometers.
    """
    MILES = "mi"
    """
    Represents distance in miles.
    """
    FEET = "ft"
    """
    Represents distance in feet.
    """

METERS = 'm' class-attribute instance-attribute

Represents distance in meters.

KILOMETERS = 'km' class-attribute instance-attribute

Represents distance in kilometers.

MILES = 'mi' class-attribute instance-attribute

Represents distance in miles.

FEET = 'ft' class-attribute instance-attribute

Represents distance in feet.

InfBound

Bases: Enum

Enumeration representing numeric and lexicographic positive and negative infinity bounds for sorted set.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class InfBound(Enum):
    """
    Enumeration representing numeric and lexicographic positive and negative infinity bounds for sorted set.
    """

    POS_INF = {"score_arg": "+inf", "lex_arg": "+"}
    """
    Positive infinity bound for sorted set.

    `score_arg`: represents numeric positive infinity (+inf).

    `lex_arg`: represents lexicographic positive infinity (+).
    """
    NEG_INF = {"score_arg": "-inf", "lex_arg": "-"}
    """
    Negative infinity bound for sorted set.

    `score_arg`: represents numeric negative infinity (-inf).

    `lex_arg`: represents lexicographic negative infinity (-).
    """

POS_INF = {'score_arg': '+inf', 'lex_arg': '+'} class-attribute instance-attribute

Positive infinity bound for sorted set.

score_arg: represents numeric positive infinity (+inf).

lex_arg: represents lexicographic positive infinity (+).

NEG_INF = {'score_arg': '-inf', 'lex_arg': '-'} class-attribute instance-attribute

Negative infinity bound for sorted set.

score_arg: represents numeric negative infinity (-inf).

lex_arg: represents lexicographic negative infinity (-).

LexBoundary

Represents a specific lexicographic boundary in a sorted set.

Parameters:

Name Type Description Default
value str

The lex value.

required
is_inclusive bool

Whether the score value is inclusive. Defaults to True.

True
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
84
85
86
87
88
89
90
91
92
93
94
95
class LexBoundary:
    """
    Represents a specific lexicographic boundary in a sorted set.

    Args:
        value (str): The lex value.
        is_inclusive (bool): Whether the score value is inclusive. Defaults to True.
    """

    def __init__(self, value: str, is_inclusive: bool = True):
        # Convert the lexicographic boundary to Valkey protocol format
        self.value = f"[{value}" if is_inclusive else f"({value}"

RangeByIndex

Represents a range by index (rank) in a sorted set.

The start and end arguments represent zero-based indexes.

Attributes:

Name Type Description
start int

The start index of the range.

end int

The end index of the range.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
class RangeByIndex:
    """
    Represents a range by index (rank) in a sorted set.

    The `start` and `end` arguments represent zero-based indexes.

    Attributes:
        start (int): The start index of the range.
        end (int): The end index of the range.
    """

    def __init__(self, start: int, end: int):
        self.start = start
        self.end = end

RangeByLex

Represents a range by lexicographical order in a sorted set.

The start and end arguments represent lexicographical boundaries.

Attributes:

Name Type Description
start Union[InfBound, LexBoundary]

The start lexicographic boundary.

end Union[InfBound, LexBoundary]

The end lexicographic boundary.

limit Optional[Limit]

The limit argument for a range query. Defaults to None. See Limit class for more information.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
class RangeByLex:
    """
    Represents a range by lexicographical order in a sorted set.

    The `start` and `end` arguments represent lexicographical boundaries.

    Attributes:
        start (Union[InfBound, LexBoundary]): The start lexicographic boundary.
        end (Union[InfBound, LexBoundary]): The end lexicographic boundary.
        limit (Optional[Limit]): The limit argument for a range query. Defaults to None. See `Limit` class
            for more information.
    """

    def __init__(
        self,
        start: Union[InfBound, LexBoundary],
        end: Union[InfBound, LexBoundary],
        limit: Optional[Limit] = None,
    ):
        self.start = (
            start.value["lex_arg"] if isinstance(start, InfBound) else start.value
        )
        self.end = end.value["lex_arg"] if isinstance(end, InfBound) else end.value
        self.limit = limit

RangeByScore

Represents a range by score in a sorted set.

The start and end arguments represent score boundaries.

Attributes:

Name Type Description
start Union[InfBound, ScoreBoundary]

The start score boundary.

end Union[InfBound, ScoreBoundary]

The end score boundary.

limit Optional[Limit]

The limit argument for a range query. Defaults to None. See Limit class for more information.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
class RangeByScore:
    """
    Represents a range by score in a sorted set.

    The `start` and `end` arguments represent score boundaries.

    Attributes:
        start (Union[InfBound, ScoreBoundary]): The start score boundary.
        end (Union[InfBound, ScoreBoundary]): The end score boundary.
        limit (Optional[Limit]): The limit argument for a range query. Defaults to None. See `Limit`
            class for more information.
    """

    def __init__(
        self,
        start: Union[InfBound, ScoreBoundary],
        end: Union[InfBound, ScoreBoundary],
        limit: Optional[Limit] = None,
    ):
        self.start = (
            start.value["score_arg"] if isinstance(start, InfBound) else start.value
        )
        self.end = end.value["score_arg"] if isinstance(end, InfBound) else end.value
        self.limit = limit

ScoreBoundary

Represents a specific numeric score boundary in a sorted set.

Parameters:

Name Type Description Default
value float

The score value.

required
is_inclusive bool

Whether the score value is inclusive. Defaults to True.

True
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
70
71
72
73
74
75
76
77
78
79
80
81
class ScoreBoundary:
    """
    Represents a specific numeric score boundary in a sorted set.

    Args:
        value (float): The score value.
        is_inclusive (bool): Whether the score value is inclusive. Defaults to True.
    """

    def __init__(self, value: float, is_inclusive: bool = True):
        # Convert the score boundary to Valkey protocol format
        self.value = str(value) if is_inclusive else f"({value}"

ScoreFilter

Bases: Enum

Defines which elements to pop from a sorted set.

ScoreFilter is a mandatory option for ZMPOP and BZMPOP.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/sorted_set.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class ScoreFilter(Enum):
    """
    Defines which elements to pop from a sorted set.

    ScoreFilter is a mandatory option for [ZMPOP](https://valkey.io/commands/zmpop)
    and [BZMPOP](https://valkey.io/commands/bzmpop).
    """

    MIN = "MIN"
    """
    Pop elements with the lowest scores.
    """
    MAX = "MAX"
    """
    Pop elements with the highest scores.
    """

MIN = 'MIN' class-attribute instance-attribute

Pop elements with the lowest scores.

MAX = 'MAX' class-attribute instance-attribute

Pop elements with the highest scores.

ExclusiveIdBound

Bases: StreamRangeBound

Exclusive (open) stream ID boundary used to specify a range of IDs to search. Stream ID bounds can be complete with a timestamp and sequence number separated by a dash ("-"), for example "1526985054069-0". Stream ID bounds can also be incomplete, with just a timestamp.

Since: Valkey version 6.2.0.

Attributes:

Name Type Description
stream_id TEncodable

The stream ID.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
class ExclusiveIdBound(StreamRangeBound):
    """
    Exclusive (open) stream ID boundary used to specify a range of IDs to search. Stream ID bounds can be complete with
    a timestamp and sequence number separated by a dash ("-"), for example "1526985054069-0". Stream ID bounds can also
    be incomplete, with just a timestamp.

    Since: Valkey version 6.2.0.

    Attributes:
        stream_id (TEncodable): The stream ID.
    """

    EXCLUSIVE_BOUND_VALKEY_API = "("

    @staticmethod
    def from_timestamp(timestamp: int) -> ExclusiveIdBound:
        """
        Creates an incomplete stream ID boundary without the sequence number for a range search.

        Args:
            timestamp (int): The stream ID timestamp.
        """
        return ExclusiveIdBound(str(timestamp))

    def __init__(self, stream_id: TEncodable):
        """
        Creates a stream ID boundary for a range search.
        """
        if isinstance(stream_id, bytes):
            stream_id = stream_id.decode("utf-8")
        self.stream_id = f"{self.EXCLUSIVE_BOUND_VALKEY_API}{stream_id}"

    def to_arg(self) -> TEncodable:
        return self.stream_id

from_timestamp(timestamp) staticmethod

Creates an incomplete stream ID boundary without the sequence number for a range search.

Parameters:

Name Type Description Default
timestamp int

The stream ID timestamp.

required
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
222
223
224
225
226
227
228
229
230
@staticmethod
def from_timestamp(timestamp: int) -> ExclusiveIdBound:
    """
    Creates an incomplete stream ID boundary without the sequence number for a range search.

    Args:
        timestamp (int): The stream ID timestamp.
    """
    return ExclusiveIdBound(str(timestamp))

IdBound

Bases: StreamRangeBound

Inclusive (closed) stream ID boundary used to specify a range of IDs to search. Stream ID bounds can be complete with a timestamp and sequence number separated by a dash ("-"), for example "1526985054069-0". Stream ID bounds can also be incomplete, with just a timestamp.

Attributes:

Name Type Description
stream_id str

The stream ID.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
class IdBound(StreamRangeBound):
    """
    Inclusive (closed) stream ID boundary used to specify a range of IDs to search. Stream ID bounds can be complete
    with a timestamp and sequence number separated by a dash ("-"), for example "1526985054069-0". Stream ID bounds can
    also be incomplete, with just a timestamp.

    Attributes:
        stream_id (str): The stream ID.
    """

    @staticmethod
    def from_timestamp(timestamp: int) -> IdBound:
        """
        Creates an incomplete stream ID boundary without the sequence number for a range search.

        Args:
            timestamp (int): The stream ID timestamp.
        """
        return IdBound(str(timestamp))

    def __init__(self, stream_id: TEncodable):
        """
        Creates a stream ID boundary for a range search.
        """
        self.stream_id = stream_id

    def to_arg(self) -> TEncodable:
        return self.stream_id

from_timestamp(timestamp) staticmethod

Creates an incomplete stream ID boundary without the sequence number for a range search.

Parameters:

Name Type Description Default
timestamp int

The stream ID timestamp.

required
Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
188
189
190
191
192
193
194
195
196
@staticmethod
def from_timestamp(timestamp: int) -> IdBound:
    """
    Creates an incomplete stream ID boundary without the sequence number for a range search.

    Args:
        timestamp (int): The stream ID timestamp.
    """
    return IdBound(str(timestamp))

MaxId

Bases: StreamRangeBound

Stream ID boundary used to specify the maximum stream entry ID. Can be used in the XRANGE or XREVRANGE commands to get the last stream ID.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
166
167
168
169
170
171
172
173
174
175
class MaxId(StreamRangeBound):
    """
    Stream ID boundary used to specify the maximum stream entry ID. Can be used in the `XRANGE` or `XREVRANGE` commands
    to get the last stream ID.
    """

    MAX_RANGE_VALKEY_API = "+"

    def to_arg(self) -> str:
        return self.MAX_RANGE_VALKEY_API

MinId

Bases: StreamRangeBound

Stream ID boundary used to specify the minimum stream entry ID. Can be used in the XRANGE or XREVRANGE commands to get the first stream ID.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
154
155
156
157
158
159
160
161
162
163
class MinId(StreamRangeBound):
    """
    Stream ID boundary used to specify the minimum stream entry ID. Can be used in the `XRANGE` or `XREVRANGE` commands
    to get the first stream ID.
    """

    MIN_RANGE_VALKEY_API = "-"

    def to_arg(self) -> str:
        return self.MIN_RANGE_VALKEY_API

StreamAddOptions

Options for adding entries to a stream.

Attributes:

Name Type Description
id Optional[TEncodable]

ID for the new entry. If set, the new entry will be added with this ID. If not specified, '*' is used.

make_stream bool

If set to False, a new stream won't be created if no stream matches the given key.

trim Optional[StreamTrimOptions]

If set, the add operation will also trim the older entries in the stream. See StreamTrimOptions.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
class StreamAddOptions:
    """
    Options for adding entries to a stream.

    Attributes:
        id (Optional[TEncodable]): ID for the new entry. If set, the new entry will be added with this ID. If not
            specified, '*' is used.
        make_stream (bool, optional): If set to False, a new stream won't be created if no stream matches the given key.
        trim (Optional[StreamTrimOptions]): If set, the add operation will also trim the older entries in the stream.
            See `StreamTrimOptions`.
    """

    def __init__(
        self,
        id: Optional[TEncodable] = None,
        make_stream: bool = True,
        trim: Optional[StreamTrimOptions] = None,
    ):
        """
        Initialize stream add options.
        """
        self.id = id
        self.make_stream = make_stream
        self.trim = trim

    def to_args(self) -> List[TEncodable]:
        """
        Convert options to arguments for the command.

        Returns:
            List[str]: List of arguments for the command.
        """
        option_args: List[TEncodable] = []
        if not self.make_stream:
            option_args.append("NOMKSTREAM")
        if self.trim:
            option_args.extend(self.trim.to_args())
        option_args.append(self.id if self.id else "*")

        return option_args

to_args()

Convert options to arguments for the command.

Returns:

Type Description
List[TEncodable]

List[str]: List of arguments for the command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def to_args(self) -> List[TEncodable]:
    """
    Convert options to arguments for the command.

    Returns:
        List[str]: List of arguments for the command.
    """
    option_args: List[TEncodable] = []
    if not self.make_stream:
        option_args.append("NOMKSTREAM")
    if self.trim:
        option_args.extend(self.trim.to_args())
    option_args.append(self.id if self.id else "*")

    return option_args

StreamClaimOptions

Options for XCLAIM.

Attributes:

Name Type Description
idle Optional[int]

Set the idle time (last time it was delivered) of the message in milliseconds. If idle is not specified, an idle of 0 is assumed, that is, the time count is reset because the message now has a new owner trying to process it.

idle_unix_time Optional[int]

This is the same as idle but instead of a relative amount of milliseconds, it sets the idle time to a specific Unix time (in milliseconds). This is useful in order to rewrite the AOF file generating XCLAIM commands.

retry_count Optional[int]

Set the retry counter to the specified value. This counter is incremented every time a message is delivered again. Normally XCLAIM does not alter this counter, which is just served to clients when the XPENDING command is called: this way clients can detect anomalies, like messages that are never processed for some reason after a big number of delivery attempts.

is_force Optional[bool]

Creates the pending message entry in the PEL even if certain specified IDs are not already in the PEL assigned to a different client. However, the message must exist in the stream, otherwise the IDs of non-existing messages are ignored.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
class StreamClaimOptions:
    """
    Options for `XCLAIM`.

    Attributes:
        idle (Optional[int]): Set the idle time (last time it was delivered) of the message in milliseconds. If idle
            is not specified, an idle of `0` is assumed, that is, the time count is reset because the message now has a
            new owner trying to process it.
        idle_unix_time (Optional[int]): This is the same as idle but instead of a relative amount of milliseconds,
            it sets the idle time to a specific Unix time (in milliseconds). This is useful in order to rewrite the AOF
            file generating `XCLAIM` commands.
        retry_count (Optional[int]): Set the retry counter to the specified value. This counter is incremented every
            time a message is delivered again. Normally `XCLAIM` does not alter this counter, which is just served to
            clients when the `XPENDING` command is called: this way clients can detect anomalies, like messages that
            are never processed for some reason after a big number of delivery attempts.
        is_force (Optional[bool]): Creates the pending message entry in the PEL even if certain specified IDs are not
            already in the PEL assigned to a different client. However, the message must exist in the stream, otherwise
            the IDs of non-existing messages are ignored.
    """

    IDLE_VALKEY_API = "IDLE"
    TIME_VALKEY_API = "TIME"
    RETRY_COUNT_VALKEY_API = "RETRYCOUNT"
    FORCE_VALKEY_API = "FORCE"
    JUST_ID_VALKEY_API = "JUSTID"

    def __init__(
        self,
        idle: Optional[int] = None,
        idle_unix_time: Optional[int] = None,
        retry_count: Optional[int] = None,
        is_force: Optional[bool] = False,
    ):
        self.idle = idle
        self.idle_unix_time = idle_unix_time
        self.retry_count = retry_count
        self.is_force = is_force

    def to_args(self) -> List[TEncodable]:
        """
        Converts options for `XCLAIM` into a List.

        Returns:
            List[str]: The options as a list of arguments for the `XCLAIM` command.
        """
        args: List[TEncodable] = []
        if self.idle:
            args.append(self.IDLE_VALKEY_API)
            args.append(str(self.idle))

        if self.idle_unix_time:
            args.append(self.TIME_VALKEY_API)
            args.append(str(self.idle_unix_time))

        if self.retry_count:
            args.append(self.RETRY_COUNT_VALKEY_API)
            args.append(str(self.retry_count))

        if self.is_force:
            args.append(self.FORCE_VALKEY_API)

        return args

to_args()

Converts options for XCLAIM into a List.

Returns:

Type Description
List[TEncodable]

List[str]: The options as a list of arguments for the XCLAIM command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def to_args(self) -> List[TEncodable]:
    """
    Converts options for `XCLAIM` into a List.

    Returns:
        List[str]: The options as a list of arguments for the `XCLAIM` command.
    """
    args: List[TEncodable] = []
    if self.idle:
        args.append(self.IDLE_VALKEY_API)
        args.append(str(self.idle))

    if self.idle_unix_time:
        args.append(self.TIME_VALKEY_API)
        args.append(str(self.idle_unix_time))

    if self.retry_count:
        args.append(self.RETRY_COUNT_VALKEY_API)
        args.append(str(self.retry_count))

    if self.is_force:
        args.append(self.FORCE_VALKEY_API)

    return args

StreamGroupOptions

Options for creating stream consumer groups. Can be used as an optional argument to XGROUP CREATE.

Attributes:

Name Type Description
make_stream bool

If set to True and the stream doesn't exist, this creates a new stream with a length of 0.

entries_read

(Optional[int]): A value representing the number of stream entries already read by the group. This option can only be specified if you are using Valkey version 7.0.0 or above.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
class StreamGroupOptions:
    """
    Options for creating stream consumer groups. Can be used as an optional argument to `XGROUP CREATE`.

    Attributes:
        make_stream (bool): If set to True and the stream doesn't exist, this creates a new stream with a
            length of 0.
        entries_read: (Optional[int]): A value representing the number of stream entries already read by the
            group. This option can only be specified if you are using Valkey version 7.0.0 or above.
    """

    MAKE_STREAM_VALKEY_API = "MKSTREAM"
    ENTRIES_READ_VALKEY_API = "ENTRIESREAD"

    def __init__(self, make_stream: bool = False, entries_read: Optional[int] = None):
        self.make_stream = make_stream
        self.entries_read = entries_read

    def to_args(self) -> List[TEncodable]:
        """
        Returns the options as a list of string arguments to be used in the `XGROUP CREATE` command.

        Returns:
            List[TEncodable]: The options as a list of arguments for the `XGROUP CREATE` command.
        """
        args: List[TEncodable] = []
        if self.make_stream is True:
            args.append(self.MAKE_STREAM_VALKEY_API)

        if self.entries_read is not None:
            args.extend([self.ENTRIES_READ_VALKEY_API, str(self.entries_read)])

        return args

to_args()

Returns the options as a list of string arguments to be used in the XGROUP CREATE command.

Returns:

Type Description
List[TEncodable]

List[TEncodable]: The options as a list of arguments for the XGROUP CREATE command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def to_args(self) -> List[TEncodable]:
    """
    Returns the options as a list of string arguments to be used in the `XGROUP CREATE` command.

    Returns:
        List[TEncodable]: The options as a list of arguments for the `XGROUP CREATE` command.
    """
    args: List[TEncodable] = []
    if self.make_stream is True:
        args.append(self.MAKE_STREAM_VALKEY_API)

    if self.entries_read is not None:
        args.extend([self.ENTRIES_READ_VALKEY_API, str(self.entries_read)])

    return args

StreamPendingOptions

Options for XPENDING that can be used to filter returned items by minimum idle time and consumer name.

Attributes:

Name Type Description
min_idle_time_ms Optional[int]

Filters pending entries by their minimum idle time in milliseconds. This option can only be specified if you are using Valkey version 6.2.0 or above.

consumer_name Optional[TEncodable]

Filters pending entries by consumer name.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
class StreamPendingOptions:
    """
    Options for `XPENDING` that can be used to filter returned items by minimum idle time and consumer name.

    Attributes:
        min_idle_time_ms (Optional[int]): Filters pending entries by their minimum idle time in milliseconds. This
            option can only be specified if you are using Valkey version 6.2.0 or above.
        consumer_name (Optional[TEncodable]): Filters pending entries by consumer name.
    """

    IDLE_TIME_VALKEY_API = "IDLE"

    def __init__(
        self,
        min_idle_time_ms: Optional[int] = None,
        consumer_name: Optional[TEncodable] = None,
    ):
        self.min_idle_time = min_idle_time_ms
        self.consumer_name = consumer_name

StreamRangeBound

Bases: ABC

Abstract Base Class used in the XPENDING, XRANGE, and XREVRANGE commands to specify the starting and ending range bound for the stream search by stream entry ID.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
140
141
142
143
144
145
146
147
148
149
150
151
class StreamRangeBound(ABC):
    """
    Abstract Base Class used in the `XPENDING`, `XRANGE`, and `XREVRANGE` commands to specify the starting and ending
    range bound for the stream search by stream entry ID.
    """

    @abstractmethod
    def to_arg(self) -> TEncodable:
        """
        Returns the stream range bound as a string argument to be used in the `XRANGE` or `XREVRANGE` commands.
        """
        pass

to_arg() abstractmethod

Returns the stream range bound as a string argument to be used in the XRANGE or XREVRANGE commands.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
146
147
148
149
150
151
@abstractmethod
def to_arg(self) -> TEncodable:
    """
    Returns the stream range bound as a string argument to be used in the `XRANGE` or `XREVRANGE` commands.
    """
    pass

StreamReadGroupOptions

Bases: StreamReadOptions

Options for reading entries from streams using a consumer group. Can be used as an optional argument to XREADGROUP.

Attributes:

Name Type Description
no_ack bool

If set, messages are not added to the Pending Entries List (PEL). This is equivalent to acknowledging the message when it is read. Equivalent to NOACK in the Valkey API.

block_ms Optional[int]

If provided, the request will be blocked for the set amount of milliseconds or until the server has the required number of entries. Equivalent to BLOCK in the Valkey API.

count Optional[int]

The maximum number of elements requested. Equivalent to COUNT in the Valkey API.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
class StreamReadGroupOptions(StreamReadOptions):
    """
    Options for reading entries from streams using a consumer group. Can be used as an optional argument to
    `XREADGROUP`.

    Attributes:
        no_ack (bool): If set, messages are not added to the Pending Entries List (PEL). This is equivalent to
            acknowledging the message when it is read. Equivalent to `NOACK` in the Valkey API.
        block_ms (Optional[int]): If provided, the request will be blocked for the set amount of milliseconds or
            until the server has the required number of entries. Equivalent to `BLOCK` in the Valkey API.
        count (Optional[int]): The maximum number of elements requested. Equivalent to `COUNT` in the Valkey API.
    """

    READ_NOACK_VALKEY_API = "NOACK"

    def __init__(
        self, no_ack=False, block_ms: Optional[int] = None, count: Optional[int] = None
    ):
        super().__init__(block_ms=block_ms, count=count)
        self.no_ack = no_ack

    def to_args(self) -> List[TEncodable]:
        """
        Returns the options as a list of string arguments to be used in the `XREADGROUP` command.

        Returns:
            List[TEncodable]: The options as a list of arguments for the `XREADGROUP` command.
        """
        args: List[TEncodable] = super().to_args()
        if self.no_ack:
            args.append(self.READ_NOACK_VALKEY_API)

        return args

to_args()

Returns the options as a list of string arguments to be used in the XREADGROUP command.

Returns:

Type Description
List[TEncodable]

List[TEncodable]: The options as a list of arguments for the XREADGROUP command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
334
335
336
337
338
339
340
341
342
343
344
345
def to_args(self) -> List[TEncodable]:
    """
    Returns the options as a list of string arguments to be used in the `XREADGROUP` command.

    Returns:
        List[TEncodable]: The options as a list of arguments for the `XREADGROUP` command.
    """
    args: List[TEncodable] = super().to_args()
    if self.no_ack:
        args.append(self.READ_NOACK_VALKEY_API)

    return args

StreamReadOptions

Options for reading entries from streams. Can be used as an optional argument to XREAD.

Attributes:

Name Type Description
block_ms Optional[int]

If provided, the request will be blocked for the set amount of milliseconds or until the server has the required number of entries. Equivalent to BLOCK in the Valkey API.

count Optional[int]

The maximum number of elements requested. Equivalent to COUNT in the Valkey API.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
class StreamReadOptions:
    """
    Options for reading entries from streams. Can be used as an optional argument to `XREAD`.

    Attributes:
        block_ms (Optional[int]): If provided, the request will be blocked for the set amount of milliseconds or
            until the server has the required number of entries. Equivalent to `BLOCK` in the Valkey API.
        count (Optional[int]): The maximum number of elements requested. Equivalent to `COUNT` in the Valkey API.
    """

    READ_COUNT_VALKEY_API = "COUNT"
    READ_BLOCK_VALKEY_API = "BLOCK"

    def __init__(self, block_ms: Optional[int] = None, count: Optional[int] = None):
        self.block_ms = block_ms
        self.count = count

    def to_args(self) -> List[TEncodable]:
        """
        Returns the options as a list of string arguments to be used in the `XREAD` command.

        Returns:
            List[TEncodable]: The options as a list of arguments for the `XREAD` command.
        """
        args: List[TEncodable] = []
        if self.block_ms is not None:
            args.extend([self.READ_BLOCK_VALKEY_API, str(self.block_ms)])

        if self.count is not None:
            args.extend([self.READ_COUNT_VALKEY_API, str(self.count)])

        return args

to_args()

Returns the options as a list of string arguments to be used in the XREAD command.

Returns:

Type Description
List[TEncodable]

List[TEncodable]: The options as a list of arguments for the XREAD command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def to_args(self) -> List[TEncodable]:
    """
    Returns the options as a list of string arguments to be used in the `XREAD` command.

    Returns:
        List[TEncodable]: The options as a list of arguments for the `XREAD` command.
    """
    args: List[TEncodable] = []
    if self.block_ms is not None:
        args.extend([self.READ_BLOCK_VALKEY_API, str(self.block_ms)])

    if self.count is not None:
        args.extend([self.READ_COUNT_VALKEY_API, str(self.count)])

    return args

StreamTrimOptions

Bases: ABC

Abstract base class for stream trim options.

Attributes:

Name Type Description
exact bool

If true, the stream will be trimmed exactly. Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.

threshold Union[TEncodable, int]

Threshold for trimming.

method str

Method for trimming (e.g., MINID, MAXLEN).

limit Optional[int]

Max number of entries to be trimmed. Defaults to None. Note: If exact is set to True, limit cannot be specified.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class StreamTrimOptions(ABC):
    """
    Abstract base class for stream trim options.

    Attributes:
        exact (bool): If `true`, the stream will be trimmed exactly.
            Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.
        threshold (Union[TEncodable, int]): Threshold for trimming.
        method (str): Method for trimming (e.g., MINID, MAXLEN).
        limit (Optional[int]): Max number of entries to be trimmed. Defaults to None.
            Note: If `exact` is set to `True`, `limit` cannot be specified.
    """

    @abstractmethod
    def __init__(
        self,
        exact: bool,
        threshold: Union[TEncodable, int],
        method: str,
        limit: Optional[int] = None,
    ):
        """
        Initialize stream trim options.
        """
        if exact and limit:
            raise ValueError(
                "If `exact` is set to `True`, `limit` cannot be specified."
            )
        self.exact = exact
        self.threshold = threshold
        self.method = method
        self.limit = limit

    def to_args(self) -> List[str]:
        """
        Convert options to arguments for the command.

        Returns:
            List[str]: List of arguments for the command.
        """
        option_args = [
            self.method,
            "=" if self.exact else "~",
            str(self.threshold),
        ]
        if self.limit is not None:
            option_args.extend(["LIMIT", str(self.limit)])
        return option_args

to_args()

Convert options to arguments for the command.

Returns:

Type Description
List[str]

List[str]: List of arguments for the command.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def to_args(self) -> List[str]:
    """
    Convert options to arguments for the command.

    Returns:
        List[str]: List of arguments for the command.
    """
    option_args = [
        self.method,
        "=" if self.exact else "~",
        str(self.threshold),
    ]
    if self.limit is not None:
        option_args.extend(["LIMIT", str(self.limit)])
    return option_args

TrimByMaxLen

Bases: StreamTrimOptions

Stream trim option to trim by maximum length.

Attributes:

Name Type Description
exact bool

If true, the stream will be trimmed exactly. Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.

threshold int

Threshold for trimming by maximum length.

limit Optional[int]

Max number of entries to be trimmed. Defaults to None. Note: If exact is set to True, limit cannot be specified.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class TrimByMaxLen(StreamTrimOptions):
    """
    Stream trim option to trim by maximum length.

    Attributes:
        exact (bool): If `true`, the stream will be trimmed exactly.
            Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.
        threshold (int): Threshold for trimming by maximum length.
        limit (Optional[int]): Max number of entries to be trimmed. Defaults to None.
            Note: If `exact` is set to `True`, `limit` cannot be specified.
    """

    def __init__(self, exact: bool, threshold: int, limit: Optional[int] = None):
        """
        Initialize trim option by maximum length.
        """
        super().__init__(exact, threshold, "MAXLEN", limit)

TrimByMinId

Bases: StreamTrimOptions

Stream trim option to trim by minimum ID.

Attributes:

Name Type Description
exact bool

If true, the stream will be trimmed exactly. Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.

threshold TEncodable

Threshold for trimming by minimum ID.

limit Optional[int]

Max number of entries to be trimmed. Defaults to None. Note: If exact is set to True, limit cannot be specified.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/commands/stream.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class TrimByMinId(StreamTrimOptions):
    """
    Stream trim option to trim by minimum ID.

    Attributes:
        exact (bool): If `true`, the stream will be trimmed exactly.
            Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.
        threshold (TEncodable): Threshold for trimming by minimum ID.
        limit (Optional[int]): Max number of entries to be trimmed. Defaults to None.
            Note: If `exact` is set to `True`, `limit` cannot be specified.
    """

    def __init__(self, exact: bool, threshold: TEncodable, limit: Optional[int] = None):
        """
        Initialize trim option by minimum ID.
        """
        super().__init__(exact, threshold, "MINID", limit)

AdvancedGlideClientConfiguration

Bases: AdvancedBaseClientConfiguration

Represents the advanced configuration settings for a Standalone Glide client.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
class AdvancedGlideClientConfiguration(AdvancedBaseClientConfiguration):
    """
    Represents the advanced configuration settings for a Standalone Glide client.
    """

    def __init__(
        self,
        connection_timeout: Optional[int] = None,
        tls_config: Optional[TlsAdvancedConfiguration] = None,
        tcp_nodelay: Optional[bool] = None,
        pubsub_reconciliation_interval: Optional[int] = None,
    ):

        super().__init__(
            connection_timeout, tls_config, tcp_nodelay, pubsub_reconciliation_interval
        )

AdvancedGlideClusterClientConfiguration

Bases: AdvancedBaseClientConfiguration

Represents the advanced configuration settings for a Glide Cluster client.

Attributes:

Name Type Description
connection_timeout Optional[int]

The duration in milliseconds to wait for a TCP/TLS connection to complete. This applies both during initial client creation and any reconnection that may occur during request processing. Note: A high connection timeout may lead to prolonged blocking of the entire command pipeline. If not explicitly set, a default value of 2000 milliseconds will be used.

tls_config Optional[TlsAdvancedConfiguration]

The advanced TLS configuration settings. This allows for more granular control of TLS behavior, such as enabling an insecure mode that bypasses certificate validation.

refresh_topology_from_initial_nodes bool

Enables refreshing the cluster topology using only the initial nodes. When this option is enabled, all topology updates (both the periodic checks and on-demand refreshes triggered by topology changes) will query only the initial nodes provided when creating the client, rather than using the internal cluster view.

pubsub_reconciliation_interval Optional[int]

The interval in milliseconds between PubSub subscription reconciliation attempts. The reconciliation process ensures that the client's desired subscriptions match the actual subscriptions on the server.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
class AdvancedGlideClusterClientConfiguration(AdvancedBaseClientConfiguration):
    """
    Represents the advanced configuration settings for a Glide Cluster client.

    Attributes:
        connection_timeout (Optional[int]): The duration in milliseconds to wait for a TCP/TLS connection to complete.
            This applies both during initial client creation and any reconnection that may occur during request processing.
            **Note**: A high connection timeout may lead to prolonged blocking of the entire command pipeline.
            If not explicitly set, a default value of 2000 milliseconds will be used.
        tls_config (Optional[TlsAdvancedConfiguration]): The advanced TLS configuration settings.
            This allows for more granular control of TLS behavior, such as enabling an insecure mode
            that bypasses certificate validation.
        refresh_topology_from_initial_nodes (bool): Enables refreshing the cluster topology using only the initial nodes.
            When this option is enabled, all topology updates (both the periodic checks and on-demand refreshes
            triggered by topology changes) will query only the initial nodes provided when creating the client, rather than using the internal cluster view.
        pubsub_reconciliation_interval (Optional[int]): The interval in milliseconds between PubSub subscription
            reconciliation attempts. The reconciliation process ensures that the client's desired subscriptions
            match the actual subscriptions on the server.
    """

    def __init__(
        self,
        connection_timeout: Optional[int] = None,
        tls_config: Optional[TlsAdvancedConfiguration] = None,
        refresh_topology_from_initial_nodes: bool = False,
        tcp_nodelay: Optional[bool] = None,
        pubsub_reconciliation_interval: Optional[int] = None,
    ):
        super().__init__(
            connection_timeout, tls_config, tcp_nodelay, pubsub_reconciliation_interval
        )
        self.refresh_topology_from_initial_nodes = refresh_topology_from_initial_nodes

    def _create_a_protobuf_conn_request(
        self, request: ConnectionRequest
    ) -> ConnectionRequest:
        super()._create_a_protobuf_conn_request(request)

        request.refresh_topology_from_initial_nodes = (
            self.refresh_topology_from_initial_nodes
        )
        return request

BackoffStrategy

Represents the strategy used to determine how and when to reconnect, in case of connection failures. The time between attempts grows exponentially, to the formula rand(0 .. factor * (exponentBase ^ N)), where N is the number of failed attempts, and rand(...) applies a jitter of up to jitter_percent% to introduce randomness and reduce retry storms. Once the maximum value is reached, that will remain the time between retry attempts until a reconnect attempt is successful. The client will attempt to reconnect indefinitely.

Attributes:

Name Type Description
num_of_retries int

Number of retry attempts that the client should perform when disconnected from the server, where the time between retries increases. Once the retries have reached the maximum value, the time between retries will remain constant until a reconnect attempt is succesful.

factor int

The multiplier that will be applied to the waiting time between each retry. This value is specified in milliseconds.

exponent_base int

The exponent base configured for the strategy.

jitter_percent Optional[int]

The Jitter percent on the calculated duration. If not set, a default value will be used.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
class BackoffStrategy:
    """
    Represents the strategy used to determine how and when to reconnect, in case of connection failures.
    The time between attempts grows exponentially, to the formula rand(0 .. factor * (exponentBase ^ N)), where N
    is the number of failed attempts, and rand(...) applies a jitter of up to jitter_percent% to introduce randomness and reduce retry storms.
    Once the maximum value is reached, that will remain the time between retry attempts until a reconnect attempt is
    successful.
    The client will attempt to reconnect indefinitely.

    Attributes:
        num_of_retries (int): Number of retry attempts that the client should perform when disconnected from the server,
            where the time between retries increases. Once the retries have reached the maximum value, the time between
            retries will remain constant until a reconnect attempt is succesful.
        factor (int): The multiplier that will be applied to the waiting time between each retry.
            This value is specified in milliseconds.
        exponent_base (int): The exponent base configured for the strategy.
        jitter_percent (Optional[int]): The Jitter percent on the calculated duration. If not set, a default value will be used.
    """

    def __init__(
        self,
        num_of_retries: int,
        factor: int,
        exponent_base: int,
        jitter_percent: Optional[int] = None,
    ):
        self.num_of_retries = num_of_retries
        self.factor = factor
        self.exponent_base = exponent_base
        self.jitter_percent = jitter_percent

CompressionBackend

Bases: Enum

Represents the compression backend to use for automatic compression.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
84
85
86
87
88
89
90
91
92
93
94
95
96
class CompressionBackend(Enum):
    """
    Represents the compression backend to use for automatic compression.
    """

    ZSTD = ProtobufCompressionBackend.ZSTD
    """
    Use zstd compression backend.
    """
    LZ4 = ProtobufCompressionBackend.LZ4
    """
    Use lz4 compression backend.
    """

ZSTD = ProtobufCompressionBackend.ZSTD class-attribute instance-attribute

Use zstd compression backend.

LZ4 = ProtobufCompressionBackend.LZ4 class-attribute instance-attribute

Use lz4 compression backend.

CompressionConfiguration dataclass

Represents the compression configuration for automatic compression of values.

Attributes:

Name Type Description
enabled bool

Whether compression is enabled. Defaults to False.

backend CompressionBackend

The compression backend to use. Defaults to CompressionBackend.ZSTD.

compression_level Optional[int]

The compression level to use. If not set, the backend's default level will be used. Valid ranges are backend-specific and validated by the Rust core. ZSTD default is 3 LZ4 default is 0

min_compression_size int

The minimum size in bytes for values to be compressed. Values smaller than this will not be compressed. Defaults to 64 bytes.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
@dataclass
class CompressionConfiguration:
    """
    Represents the compression configuration for automatic compression of values.

    Attributes:
        enabled (bool): Whether compression is enabled. Defaults to False.
        backend (CompressionBackend): The compression backend to use. Defaults to CompressionBackend.ZSTD.
        compression_level (Optional[int]): The compression level to use. If not set, the backend's default level will be used.
            Valid ranges are backend-specific and validated by the Rust core.
            ZSTD default is 3
            LZ4 default is 0
        min_compression_size (int): The minimum size in bytes for values to be compressed. Values smaller than this will not be compressed. Defaults to 64 bytes.
    """

    enabled: bool = False
    backend: CompressionBackend = CompressionBackend.ZSTD
    compression_level: Optional[int] = None
    min_compression_size: int = 64

    def __post_init__(self) -> None:
        """Validate compression configuration parameters."""
        self._validate_configuration()

    def _validate_configuration(self) -> None:
        """
        Validates the compression configuration parameters.

        Raises:
            ConfigurationError: If any configuration parameter is invalid.
        """
        min_size = _get_min_compressed_size_cached()
        if self.min_compression_size < min_size:
            raise ConfigurationError(
                f"min_compression_size should be at least {min_size} bytes"
            )

        # Note: compression_level validation is performed by the Rust core,
        # which uses the actual compression library's valid ranges.
        # This ensures the validation stays in sync with library updates.

    def _to_protobuf(self) -> ProtobufCompressionConfig:
        """
        Converts the compression configuration to protobuf format.

        Returns:
            ProtobufCompressionConfig: The protobuf compression configuration.

        Raises:
            ConfigurationError: If any configuration parameter is invalid.
        """
        # Validate configuration before converting to protobuf
        # This protects against modifications made after __post_init__
        self._validate_configuration()

        config = ProtobufCompressionConfig()
        config.enabled = self.enabled
        config.backend = self.backend.value
        config.min_compression_size = self.min_compression_size

        if self.compression_level is not None:
            config.compression_level = self.compression_level

        return config

GlideClientConfiguration

Bases: BaseClientConfiguration

Represents the configuration settings for a Standalone Glide client.

Attributes:

Name Type Description
addresses List[NodeAddress]

DNS Addresses and ports of known nodes in the cluster. Only nodes whose addresses were provided will be used by the client. For example::

[
    NodeAddress("sample-address-0001.use1.cache.amazonaws.com", 6379),
    NodeAddress("sample-address-0002.use1.cache.amazonaws.com", 6379)
]
use_tls bool

True if communication with the cluster should use Transport Level Security. Please use AdvancedGlideClusterClientConfiguration.

credentials ServerCredentials

Credentials for authentication process. If none are set, the client will not authenticate itself with the server.

read_from ReadFrom

If not set, PRIMARY will be used.

request_timeout Optional[int]

The duration in milliseconds that the client should wait for a request to complete. This duration encompasses sending the request, awaiting for a response from the server, and any required reconnection or retries. If the specified timeout is exceeded for a pending request, it will result in a timeout error. If not explicitly set, a default value of 250 milliseconds will be used.

reconnect_strategy Optional[BackoffStrategy]

Strategy used to determine how and when to reconnect, in case of connection failures. If not set, a default backoff strategy will be used.

database_id Optional[int]

Index of the logical database to connect to.

client_name Optional[str]

Client name to be used for the client. Will be used with CLIENT SETNAME command during connection establishment.

protocol ProtocolVersion

The version of the RESP protocol to communicate with the server.

pubsub_subscriptions Optional[PubSubSubscriptions]

Pubsub subscriptions to be used for the client. Will be applied via SUBSCRIBE/PSUBSCRIBE commands during connection establishment.

inflight_requests_limit Optional[int]

The maximum number of concurrent requests allowed to be in-flight (sent but not yet completed). This limit is used to control the memory usage and prevent the client from overwhelming the server or getting stuck in case of a queue backlog. If not set, a default value will be used.

client_az Optional[str]

Availability Zone of the client. If ReadFrom strategy is AZAffinity, this setting ensures that readonly commands are directed to replicas within the specified AZ if exits. If ReadFrom strategy is AZAffinityReplicasAndPrimary, this setting ensures that readonly commands are directed to nodes (first replicas then primary) within the specified AZ if they exist.

advanced_config Optional[AdvancedGlideClientConfiguration]

Advanced configuration settings for the client, see AdvancedGlideClientConfiguration.

compression Optional[CompressionConfiguration]

Configuration for automatic compression of values. When enabled, the client will automatically compress values for set-type commands and decompress values for get-type commands. This can reduce bandwidth usage and storage requirements. If not set, compression is disabled.

read_only bool

When True, enables read-only mode for the standalone client. In read-only mode: - The client skips primary node detection (INFO REPLICATION command) - Write commands are blocked and will return an error - All connected nodes are treated as valid read targets - If no ReadFrom strategy is specified, defaults to PreferReplica This is useful for connecting to replica-only deployments or when you want to prevent accidental write operations. Note: read_only mode is not compatible with AZAffinity or AZAffinityReplicasAndPrimary read strategies. Defaults to False.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
class GlideClientConfiguration(BaseClientConfiguration):
    """
    Represents the configuration settings for a Standalone Glide client.

    Attributes:
        addresses (List[NodeAddress]): DNS Addresses and ports of known nodes in the cluster.
            Only nodes whose addresses were provided will be used by the client.
            For example::

                [
                    NodeAddress("sample-address-0001.use1.cache.amazonaws.com", 6379),
                    NodeAddress("sample-address-0002.use1.cache.amazonaws.com", 6379)
                ]

        use_tls (bool): True if communication with the cluster should use Transport Level Security.
                Please use `AdvancedGlideClusterClientConfiguration`.
        credentials (ServerCredentials): Credentials for authentication process.
                If none are set, the client will not authenticate itself with the server.
        read_from (ReadFrom): If not set, `PRIMARY` will be used.
        request_timeout (Optional[int]):  The duration in milliseconds that the client should wait for a request to complete.
                This duration encompasses sending the request, awaiting for a response from the server, and any required
                reconnection or retries.
                If the specified timeout is exceeded for a pending request, it will result in a timeout error.
                If not explicitly set, a default value of 250 milliseconds will be used.
        reconnect_strategy (Optional[BackoffStrategy]): Strategy used to determine how and when to reconnect, in case of
            connection failures.
            If not set, a default backoff strategy will be used.
        database_id (Optional[int]): Index of the logical database to connect to.
        client_name (Optional[str]): Client name to be used for the client. Will be used with CLIENT SETNAME command during
            connection establishment.
        protocol (ProtocolVersion): The version of the RESP protocol to communicate with the server.
        pubsub_subscriptions (Optional[GlideClientConfiguration.PubSubSubscriptions]): Pubsub subscriptions to be used for the
                client.
                Will be applied via SUBSCRIBE/PSUBSCRIBE commands during connection establishment.
        inflight_requests_limit (Optional[int]): The maximum number of concurrent requests allowed to be in-flight
            (sent but not yet completed).
            This limit is used to control the memory usage and prevent the client from overwhelming the server or getting
            stuck in case of a queue backlog.
            If not set, a default value will be used.
        client_az (Optional[str]): Availability Zone of the client.
            If ReadFrom strategy is AZAffinity, this setting ensures that readonly commands are directed to replicas within
            the specified AZ if exits.
            If ReadFrom strategy is AZAffinityReplicasAndPrimary, this setting ensures that readonly commands are directed to
            nodes (first replicas then primary) within the specified AZ if they exist.
        advanced_config (Optional[AdvancedGlideClientConfiguration]): Advanced configuration settings for the client,
            see `AdvancedGlideClientConfiguration`.
        compression (Optional[CompressionConfiguration]): Configuration for automatic compression of values.
            When enabled, the client will automatically compress values for set-type commands and decompress
            values for get-type commands. This can reduce bandwidth usage and storage requirements.
            If not set, compression is disabled.
        read_only (bool): When True, enables read-only mode for the standalone client.
            In read-only mode:
            - The client skips primary node detection (INFO REPLICATION command)
            - Write commands are blocked and will return an error
            - All connected nodes are treated as valid read targets
            - If no ReadFrom strategy is specified, defaults to PreferReplica
            This is useful for connecting to replica-only deployments or when you want to
            prevent accidental write operations.
            Note: read_only mode is not compatible with AZAffinity or AZAffinityReplicasAndPrimary
            read strategies.
            Defaults to False.
    """

    class PubSubChannelModes(IntEnum):
        """
        Describes pubsub subsciption modes.
        See [valkey.io](https://valkey.io/docs/topics/pubsub/) for more details
        """

        Exact = 0
        """ Use exact channel names """
        Pattern = 1
        """ Use channel name patterns """

    @dataclass
    class PubSubSubscriptions:
        """Describes pubsub configuration for standalone mode client.

        Attributes:
            channels_and_patterns (Dict[GlideClientConfiguration.PubSubChannelModes, Set[str]]):
                Channels and patterns by modes.
            callback (Optional[Callable[[PubSubMsg, Any], None]]):
                Optional callback to accept the incomming messages.
            context (Any):
                Arbitrary context to pass to the callback.
        """

        channels_and_patterns: Dict[
            GlideClientConfiguration.PubSubChannelModes, Set[str]
        ]
        callback: Optional[Callable[[PubSubMsg, Any], None]]
        context: Any

    @dataclass
    class PubSubState:
        desired_subscriptions: Dict[
            GlideClientConfiguration.PubSubChannelModes, Set[str]
        ]
        actual_subscriptions: Dict[
            GlideClientConfiguration.PubSubChannelModes, Set[str]
        ]

    def __init__(
        self,
        addresses: List[NodeAddress],
        use_tls: bool = False,
        credentials: Optional[ServerCredentials] = None,
        read_from: ReadFrom = ReadFrom.PRIMARY,
        request_timeout: Optional[int] = None,
        reconnect_strategy: Optional[BackoffStrategy] = None,
        database_id: Optional[int] = None,
        client_name: Optional[str] = None,
        protocol: ProtocolVersion = ProtocolVersion.RESP3,
        pubsub_subscriptions: Optional[PubSubSubscriptions] = None,
        inflight_requests_limit: Optional[int] = None,
        client_az: Optional[str] = None,
        advanced_config: Optional[AdvancedGlideClientConfiguration] = None,
        lazy_connect: Optional[bool] = None,
        compression: Optional[CompressionConfiguration] = None,
        read_only: bool = False,
    ):
        super().__init__(
            addresses=addresses,
            use_tls=use_tls,
            credentials=credentials,
            read_from=read_from,
            request_timeout=request_timeout,
            reconnect_strategy=reconnect_strategy,
            database_id=database_id,
            client_name=client_name,
            protocol=protocol,
            inflight_requests_limit=inflight_requests_limit,
            client_az=client_az,
            advanced_config=advanced_config,
            lazy_connect=lazy_connect,
            compression=compression,
        )
        self.pubsub_subscriptions = pubsub_subscriptions
        self.read_only = read_only

    def _create_a_protobuf_conn_request(
        self, cluster_mode: bool = False
    ) -> ConnectionRequest:
        assert cluster_mode is False
        request = super()._create_a_protobuf_conn_request(cluster_mode)

        # Set read_only mode
        request.read_only = self.read_only

        if self.pubsub_subscriptions:
            if self.protocol == ProtocolVersion.RESP2:
                raise ConfigurationError(
                    "PubSub subscriptions require RESP3 protocol, but RESP2 was configured."
                )
            if (
                self.pubsub_subscriptions.context is not None
                and not self.pubsub_subscriptions.callback
            ):
                raise ConfigurationError(
                    "PubSub subscriptions with a context require a callback function to be configured."
                )
            for (
                channel_type,
                channels_patterns,
            ) in self.pubsub_subscriptions.channels_and_patterns.items():
                entry = request.pubsub_subscriptions.channels_or_patterns_by_type[
                    int(channel_type)
                ]
                for channel_pattern in channels_patterns:
                    entry.channels_or_patterns.append(str.encode(channel_pattern))

        return request

    def _get_pubsub_callback_and_context(
        self,
    ) -> Tuple[Optional[Callable[[PubSubMsg, Any], None]], Any]:
        if self.pubsub_subscriptions:
            return self.pubsub_subscriptions.callback, self.pubsub_subscriptions.context
        return None, None

PubSubChannelModes

Bases: IntEnum

Describes pubsub subsciption modes. See valkey.io for more details

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
883
884
885
886
887
888
889
890
891
892
class PubSubChannelModes(IntEnum):
    """
    Describes pubsub subsciption modes.
    See [valkey.io](https://valkey.io/docs/topics/pubsub/) for more details
    """

    Exact = 0
    """ Use exact channel names """
    Pattern = 1
    """ Use channel name patterns """

Exact = 0 class-attribute instance-attribute

Use exact channel names

Pattern = 1 class-attribute instance-attribute

Use channel name patterns

PubSubSubscriptions dataclass

Describes pubsub configuration for standalone mode client.

Attributes:

Name Type Description
channels_and_patterns Dict[PubSubChannelModes, Set[str]]

Channels and patterns by modes.

callback Optional[Callable[[PubSubMsg, Any], None]]

Optional callback to accept the incomming messages.

context Any

Arbitrary context to pass to the callback.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
@dataclass
class PubSubSubscriptions:
    """Describes pubsub configuration for standalone mode client.

    Attributes:
        channels_and_patterns (Dict[GlideClientConfiguration.PubSubChannelModes, Set[str]]):
            Channels and patterns by modes.
        callback (Optional[Callable[[PubSubMsg, Any], None]]):
            Optional callback to accept the incomming messages.
        context (Any):
            Arbitrary context to pass to the callback.
    """

    channels_and_patterns: Dict[
        GlideClientConfiguration.PubSubChannelModes, Set[str]
    ]
    callback: Optional[Callable[[PubSubMsg, Any], None]]
    context: Any

GlideClusterClientConfiguration

Bases: BaseClientConfiguration

Represents the configuration settings for a Cluster Glide client.

Attributes:

Name Type Description
addresses List[NodeAddress]

DNS Addresses and ports of known nodes in the cluster. The list can be partial, as the client will attempt to map out the cluster and find all nodes. For example::

[
    NodeAddress("sample-address-0001.use1.cache.amazonaws.com", 6379),
]
use_tls bool

True if communication with the cluster should use Transport Level Security. For advanced tls configuration, please use AdvancedGlideClusterClientConfiguration.

credentials ServerCredentials

Credentials for authentication process. If none are set, the client will not authenticate itself with the server.

read_from ReadFrom

If not set, PRIMARY will be used.

request_timeout Optional[int]

The duration in milliseconds that the client should wait for a request to complete. This duration encompasses sending the request, awaiting for a response from the server, and any required reconnection or retries. If the specified timeout is exceeded for a pending request, it will result in a timeout error. If not explicitly set, a default value of 250 milliseconds will be used.

reconnect_strategy Optional[BackoffStrategy]

Strategy used to determine how and when to reconnect, in case of connection failures. If not set, a default backoff strategy will be used.

database_id Optional[int]

Index of the logical database to connect to.

client_name Optional[str]

Client name to be used for the client. Will be used with CLIENT SETNAME command during connection establishment.

protocol ProtocolVersion

The version of the RESP protocol to communicate with the server.

periodic_checks Union[PeriodicChecksStatus, PeriodicChecksManualInterval]

Configure the periodic topology checks. These checks evaluate changes in the cluster's topology, triggering a slot refresh when detected. Periodic checks ensure a quick and efficient process by querying a limited number of nodes. Defaults to PeriodicChecksStatus.ENABLED_DEFAULT_CONFIGS.

pubsub_subscriptions Optional[PubSubSubscriptions]

Pubsub subscriptions to be used for the client. Will be applied via SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE commands during connection establishment.

inflight_requests_limit Optional[int]

The maximum number of concurrent requests allowed to be in-flight (sent but not yet completed). This limit is used to control the memory usage and prevent the client from overwhelming the server or getting stuck in case of a queue backlog. If not set, a default value will be used.

client_az Optional[str]

Availability Zone of the client. If ReadFrom strategy is AZAffinity, this setting ensures that readonly commands are directed to replicas within the specified AZ if exits. If ReadFrom strategy is AZAffinityReplicasAndPrimary, this setting ensures that readonly commands are directed to nodes (first replicas then primary) within the specified AZ if they exist.

advanced_config Optional[AdvancedGlideClusterClientConfiguration])

Advanced configuration settings for the client, see AdvancedGlideClusterClientConfiguration.

compression Optional[CompressionConfiguration]

Configuration for automatic compression of values. When enabled, the client will automatically compress values for set-type commands and decompress values for get-type commands. This can reduce bandwidth usage and storage requirements. If not set, compression is disabled.

Note

Currently, the reconnection strategy in cluster mode is not configurable, and exponential backoff with fixed values is used.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
class GlideClusterClientConfiguration(BaseClientConfiguration):
    """
    Represents the configuration settings for a Cluster Glide client.

    Attributes:
        addresses (List[NodeAddress]): DNS Addresses and ports of known nodes in the cluster.
            The list can be partial, as the client will attempt to map out the cluster and find all nodes.
            For example::

                [
                    NodeAddress("sample-address-0001.use1.cache.amazonaws.com", 6379),
                ]

        use_tls (bool): True if communication with the cluster should use Transport Level Security.
                For advanced tls configuration, please use `AdvancedGlideClusterClientConfiguration`.
        credentials (ServerCredentials): Credentials for authentication process.
                If none are set, the client will not authenticate itself with the server.
        read_from (ReadFrom): If not set, `PRIMARY` will be used.
        request_timeout (Optional[int]):  The duration in milliseconds that the client should wait for a request to complete.
            This duration encompasses sending the request, awaiting for a response from the server, and any required
            reconnection or retries.
            If the specified timeout is exceeded for a pending request, it will result in a timeout error. If not explicitly
            set, a default value of 250 milliseconds will be used.
        reconnect_strategy (Optional[BackoffStrategy]): Strategy used to determine how and when to reconnect, in case of
            connection failures.
            If not set, a default backoff strategy will be used.
        database_id (Optional[int]): Index of the logical database to connect to.
        client_name (Optional[str]): Client name to be used for the client. Will be used with CLIENT SETNAME command during
            connection establishment.
        protocol (ProtocolVersion): The version of the RESP protocol to communicate with the server.
        periodic_checks (Union[PeriodicChecksStatus, PeriodicChecksManualInterval]): Configure the periodic topology checks.
            These checks evaluate changes in the cluster's topology, triggering a slot refresh when detected.
            Periodic checks ensure a quick and efficient process by querying a limited number of nodes.
            Defaults to PeriodicChecksStatus.ENABLED_DEFAULT_CONFIGS.
        pubsub_subscriptions (Optional[GlideClusterClientConfiguration.PubSubSubscriptions]): Pubsub subscriptions to be used
            for the client.
            Will be applied via SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE commands during connection establishment.
        inflight_requests_limit (Optional[int]): The maximum number of concurrent requests allowed to be in-flight
            (sent but not yet completed).
            This limit is used to control the memory usage and prevent the client from overwhelming the server or getting
            stuck in case of a queue backlog.
            If not set, a default value will be used.
        client_az (Optional[str]): Availability Zone of the client.
            If ReadFrom strategy is AZAffinity, this setting ensures that readonly commands are directed to replicas within
            the specified AZ if exits.
            If ReadFrom strategy is AZAffinityReplicasAndPrimary, this setting ensures that readonly commands are directed to
            nodes (first replicas then primary) within the specified AZ if they exist.
        advanced_config (Optional[AdvancedGlideClusterClientConfiguration]) : Advanced configuration settings for the client,
            see `AdvancedGlideClusterClientConfiguration`.
        compression (Optional[CompressionConfiguration]): Configuration for automatic compression of values.
            When enabled, the client will automatically compress values for set-type commands and decompress
            values for get-type commands. This can reduce bandwidth usage and storage requirements.
            If not set, compression is disabled.


    Note:
        Currently, the reconnection strategy in cluster mode is not configurable, and exponential backoff
        with fixed values is used.
    """

    class PubSubChannelModes(IntEnum):
        """
        Describes pubsub subsciption modes.
        See [valkey.io](https://valkey.io/docs/topics/pubsub/) for more details
        """

        Exact = 0
        """ Use exact channel names """
        Pattern = 1
        """ Use channel name patterns """
        Sharded = 2
        """ Use sharded pubsub. Available since Valkey version 7.0. """

    @dataclass
    class PubSubSubscriptions:
        """Describes pubsub configuration for cluster mode client.

        Attributes:
            channels_and_patterns (Dict[GlideClusterClientConfiguration.PubSubChannelModes, Set[str]]):
                Channels and patterns by modes.
            callback (Optional[Callable[[PubSubMsg, Any], None]]):
                Optional callback to accept the incoming messages.
            context (Any):
                Arbitrary context to pass to the callback.
        """

        channels_and_patterns: Dict[
            GlideClusterClientConfiguration.PubSubChannelModes, Set[str]
        ]
        callback: Optional[Callable[[PubSubMsg, Any], None]]
        context: Any

    @dataclass
    class PubSubState:
        desired_subscriptions: Dict[
            GlideClusterClientConfiguration.PubSubChannelModes, Set[str]
        ]
        actual_subscriptions: Dict[
            GlideClusterClientConfiguration.PubSubChannelModes, Set[str]
        ]

    def __init__(
        self,
        addresses: List[NodeAddress],
        use_tls: bool = False,
        credentials: Optional[ServerCredentials] = None,
        read_from: ReadFrom = ReadFrom.PRIMARY,
        request_timeout: Optional[int] = None,
        reconnect_strategy: Optional[BackoffStrategy] = None,
        database_id: Optional[int] = None,
        client_name: Optional[str] = None,
        protocol: ProtocolVersion = ProtocolVersion.RESP3,
        periodic_checks: Union[
            PeriodicChecksStatus, PeriodicChecksManualInterval
        ] = PeriodicChecksStatus.ENABLED_DEFAULT_CONFIGS,
        pubsub_subscriptions: Optional[PubSubSubscriptions] = None,
        inflight_requests_limit: Optional[int] = None,
        client_az: Optional[str] = None,
        advanced_config: Optional[AdvancedGlideClusterClientConfiguration] = None,
        lazy_connect: Optional[bool] = None,
        compression: Optional[CompressionConfiguration] = None,
    ):
        super().__init__(
            addresses=addresses,
            use_tls=use_tls,
            credentials=credentials,
            read_from=read_from,
            request_timeout=request_timeout,
            reconnect_strategy=reconnect_strategy,
            database_id=database_id,
            client_name=client_name,
            protocol=protocol,
            inflight_requests_limit=inflight_requests_limit,
            client_az=client_az,
            advanced_config=advanced_config,
            lazy_connect=lazy_connect,
            compression=compression,
        )
        self.periodic_checks = periodic_checks
        self.pubsub_subscriptions = pubsub_subscriptions

    def _create_a_protobuf_conn_request(
        self, cluster_mode: bool = False
    ) -> ConnectionRequest:
        assert cluster_mode is True
        request = super()._create_a_protobuf_conn_request(cluster_mode)
        if type(self.periodic_checks) is PeriodicChecksManualInterval:
            request.periodic_checks_manual_interval.duration_in_sec = (
                self.periodic_checks.duration_in_sec
            )
        elif self.periodic_checks == PeriodicChecksStatus.DISABLED:
            request.periodic_checks_disabled.SetInParent()

        if self.pubsub_subscriptions:
            if self.protocol == ProtocolVersion.RESP2:
                raise ConfigurationError(
                    "PubSub subscriptions require RESP3 protocol, but RESP2 was configured."
                )
            if (
                self.pubsub_subscriptions.context is not None
                and not self.pubsub_subscriptions.callback
            ):
                raise ConfigurationError(
                    "PubSub subscriptions with a context require a callback function to be configured."
                )
            for (
                channel_type,
                channels_patterns,
            ) in self.pubsub_subscriptions.channels_and_patterns.items():
                entry = request.pubsub_subscriptions.channels_or_patterns_by_type[
                    int(channel_type)
                ]
                for channel_pattern in channels_patterns:
                    entry.channels_or_patterns.append(str.encode(channel_pattern))

        if self.lazy_connect is not None:
            request.lazy_connect = self.lazy_connect
        return request

    def _get_pubsub_callback_and_context(
        self,
    ) -> Tuple[Optional[Callable[[PubSubMsg, Any], None]], Any]:
        if self.pubsub_subscriptions:
            return self.pubsub_subscriptions.callback, self.pubsub_subscriptions.context
        return None, None

PubSubChannelModes

Bases: IntEnum

Describes pubsub subsciption modes. See valkey.io for more details

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
class PubSubChannelModes(IntEnum):
    """
    Describes pubsub subsciption modes.
    See [valkey.io](https://valkey.io/docs/topics/pubsub/) for more details
    """

    Exact = 0
    """ Use exact channel names """
    Pattern = 1
    """ Use channel name patterns """
    Sharded = 2
    """ Use sharded pubsub. Available since Valkey version 7.0. """

Exact = 0 class-attribute instance-attribute

Use exact channel names

Pattern = 1 class-attribute instance-attribute

Use channel name patterns

Sharded = 2 class-attribute instance-attribute

Use sharded pubsub. Available since Valkey version 7.0.

PubSubSubscriptions dataclass

Describes pubsub configuration for cluster mode client.

Attributes:

Name Type Description
channels_and_patterns Dict[PubSubChannelModes, Set[str]]

Channels and patterns by modes.

callback Optional[Callable[[PubSubMsg, Any], None]]

Optional callback to accept the incoming messages.

context Any

Arbitrary context to pass to the callback.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
@dataclass
class PubSubSubscriptions:
    """Describes pubsub configuration for cluster mode client.

    Attributes:
        channels_and_patterns (Dict[GlideClusterClientConfiguration.PubSubChannelModes, Set[str]]):
            Channels and patterns by modes.
        callback (Optional[Callable[[PubSubMsg, Any], None]]):
            Optional callback to accept the incoming messages.
        context (Any):
            Arbitrary context to pass to the callback.
    """

    channels_and_patterns: Dict[
        GlideClusterClientConfiguration.PubSubChannelModes, Set[str]
    ]
    callback: Optional[Callable[[PubSubMsg, Any], None]]
    context: Any

IamAuthConfig

Configuration settings for IAM authentication.

Attributes:

Name Type Description
cluster_name str

The name of the ElastiCache/MemoryDB cluster.

service ServiceType

The type of service being used (ElastiCache or MemoryDB).

region str

The AWS region where the ElastiCache/MemoryDB cluster is located.

refresh_interval_seconds Optional[int]

Optional refresh interval in seconds for renewing IAM authentication tokens. If not provided, the core will use a default value of 300 seconds (5 min).

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
class IamAuthConfig:
    """
    Configuration settings for IAM authentication.

    Attributes:
        cluster_name (str): The name of the ElastiCache/MemoryDB cluster.
        service (ServiceType): The type of service being used (ElastiCache or MemoryDB).
        region (str): The AWS region where the ElastiCache/MemoryDB cluster is located.
        refresh_interval_seconds (Optional[int]): Optional refresh interval in seconds for renewing IAM authentication tokens.
            If not provided, the core will use a default value of 300 seconds (5 min).
    """

    def __init__(
        self,
        cluster_name: str,
        service: ServiceType,
        region: str,
        refresh_interval_seconds: Optional[int] = None,
    ):
        self.cluster_name = cluster_name
        self.service = service
        self.region = region
        self.refresh_interval_seconds = refresh_interval_seconds

NodeAddress

Represents the address and port of a node in the cluster.

Attributes:

Name Type Description
host str

The server host. Defaults to "localhost".

port int

The server port. Defaults to 6379.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
29
30
31
32
33
34
35
36
37
38
39
40
class NodeAddress:
    """
    Represents the address and port of a node in the cluster.

    Attributes:
        host (str, optional): The server host. Defaults to "localhost".
        port (int, optional): The server port. Defaults to 6379.
    """

    def __init__(self, host: str = "localhost", port: int = 6379):
        self.host = host
        self.port = port

PeriodicChecksManualInterval

Represents a manually configured interval for periodic checks.

Attributes:

Name Type Description
duration_in_sec int

The duration in seconds for the interval between periodic checks.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
328
329
330
331
332
333
334
335
336
337
class PeriodicChecksManualInterval:
    """
    Represents a manually configured interval for periodic checks.

    Attributes:
        duration_in_sec (int): The duration in seconds for the interval between periodic checks.
    """

    def __init__(self, duration_in_sec: int) -> None:
        self.duration_in_sec = duration_in_sec

PeriodicChecksStatus

Bases: Enum

Represents the cluster's periodic checks status. To configure specific interval, see PeriodicChecksManualInterval.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
class PeriodicChecksStatus(Enum):
    """
    Represents the cluster's periodic checks status.
    To configure specific interval, see PeriodicChecksManualInterval.
    """

    ENABLED_DEFAULT_CONFIGS = 0
    """
    Enables the periodic checks with the default configurations.
    """
    DISABLED = 1
    """
    Disables the periodic checks.
    """

ENABLED_DEFAULT_CONFIGS = 0 class-attribute instance-attribute

Enables the periodic checks with the default configurations.

DISABLED = 1 class-attribute instance-attribute

Disables the periodic checks.

ProtocolVersion

Bases: Enum

Represents the communication protocol with the server.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
69
70
71
72
73
74
75
76
77
78
79
80
81
class ProtocolVersion(Enum):
    """
    Represents the communication protocol with the server.
    """

    RESP2 = SentProtocolVersion.RESP2
    """
    Communicate using RESP2.
    """
    RESP3 = SentProtocolVersion.RESP3
    """
    Communicate using RESP3.
    """

RESP2 = SentProtocolVersion.RESP2 class-attribute instance-attribute

Communicate using RESP2.

RESP3 = SentProtocolVersion.RESP3 class-attribute instance-attribute

Communicate using RESP3.

ReadFrom

Bases: Enum

Represents the client's read from strategy.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class ReadFrom(Enum):
    """
    Represents the client's read from strategy.
    """

    PRIMARY = ProtobufReadFrom.Primary
    """
    Always get from primary, in order to get the freshest data.
    """
    PREFER_REPLICA = ProtobufReadFrom.PreferReplica
    """
    Spread the requests between all replicas in a round robin manner.
    If no replica is available, route the requests to the primary.
    """
    AZ_AFFINITY = ProtobufReadFrom.AZAffinity
    """
    Spread the read requests between replicas in the same client's AZ (Aviliablity zone) in a round robin manner,
    falling back to other replicas or the primary if needed
    """
    AZ_AFFINITY_REPLICAS_AND_PRIMARY = ProtobufReadFrom.AZAffinityReplicasAndPrimary
    """
    Spread the read requests among nodes within the client's Availability Zone (AZ) in a round robin manner,
    prioritizing local replicas, then the local primary, and falling back to any replica or the primary if needed.
    """

PRIMARY = ProtobufReadFrom.Primary class-attribute instance-attribute

Always get from primary, in order to get the freshest data.

PREFER_REPLICA = ProtobufReadFrom.PreferReplica class-attribute instance-attribute

Spread the requests between all replicas in a round robin manner. If no replica is available, route the requests to the primary.

AZ_AFFINITY = ProtobufReadFrom.AZAffinity class-attribute instance-attribute

Spread the read requests between replicas in the same client's AZ (Aviliablity zone) in a round robin manner, falling back to other replicas or the primary if needed

AZ_AFFINITY_REPLICAS_AND_PRIMARY = ProtobufReadFrom.AZAffinityReplicasAndPrimary class-attribute instance-attribute

Spread the read requests among nodes within the client's Availability Zone (AZ) in a round robin manner, prioritizing local replicas, then the local primary, and falling back to any replica or the primary if needed.

ServerCredentials

Represents the credentials for connecting to a server.

Exactly one of the following authentication modes must be provided
  • Password-based authentication: Use password (and optionally username)
  • IAM authentication: Use username (required) and iam_config

These modes are mutually exclusive - you cannot use both simultaneously.

Attributes:

Name Type Description
password Optional[str]

The password that will be used for authenticating connections to the servers. Mutually exclusive with iam_config. Either password or iam_config must be provided.

username Optional[str]

The username that will be used for authenticating connections to the servers. If not supplied for password-based authentication, "default" will be used. Required for IAM authentication.

iam_config Optional[IamAuthConfig]

IAM authentication configuration. Mutually exclusive with password. Either password or iam_config must be provided. The client will automatically generate and refresh the authentication token based on the provided configuration.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
class ServerCredentials:
    """
    Represents the credentials for connecting to a server.

    Exactly one of the following authentication modes must be provided:
        - Password-based authentication: Use password (and optionally username)
        - IAM authentication: Use username (required) and iam_config

    These modes are mutually exclusive - you cannot use both simultaneously.

    Attributes:
        password (Optional[str]): The password that will be used for authenticating connections to the servers.
            Mutually exclusive with iam_config. Either password or iam_config must be provided.
        username (Optional[str]): The username that will be used for authenticating connections to the servers.
            If not supplied for password-based authentication, "default" will be used.
            Required for IAM authentication.
        iam_config (Optional[IamAuthConfig]): IAM authentication configuration. Mutually exclusive with password.
            Either password or iam_config must be provided.
            The client will automatically generate and refresh the authentication token based on the provided configuration.
    """

    def __init__(
        self,
        password: Optional[str] = None,
        username: Optional[str] = None,
        iam_config: Optional[IamAuthConfig] = None,
    ):
        # Validate mutual exclusivity
        if password is not None and iam_config is not None:
            raise ConfigurationError(
                "password and iam_config are mutually exclusive. Use either password-based or IAM authentication, not both."
            )

        # Validate IAM requires username
        if iam_config is not None and not username:
            raise ConfigurationError("username is required for IAM authentication.")

        # At least one authentication method must be provided
        if password is None and iam_config is None:
            raise ConfigurationError(
                "Either password or iam_config must be provided for authentication."
            )

        self.password = password
        self.username = username
        self.iam_config = iam_config

    def is_iam_auth(self) -> bool:
        """Returns True if this credential is configured for IAM authentication."""
        return self.iam_config is not None

is_iam_auth()

Returns True if this credential is configured for IAM authentication.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
323
324
325
def is_iam_auth(self) -> bool:
    """Returns True if this credential is configured for IAM authentication."""
    return self.iam_config is not None

ServiceType

Bases: Enum

Represents the types of AWS services that can be used for IAM authentication.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
240
241
242
243
244
245
246
247
248
class ServiceType(Enum):
    """
    Represents the types of AWS services that can be used for IAM authentication.
    """

    ELASTICACHE = 0
    """Amazon ElastiCache service."""
    MEMORYDB = 1
    """Amazon MemoryDB service."""

ELASTICACHE = 0 class-attribute instance-attribute

Amazon ElastiCache service.

MEMORYDB = 1 class-attribute instance-attribute

Amazon MemoryDB service.

TlsAdvancedConfiguration

Represents advanced TLS configuration settings.

Attributes:

Name Type Description
use_insecure_tls Optional[bool]

Whether to bypass TLS certificate verification.

  • When set to True, the client skips certificate validation. This is useful when connecting to servers or clusters using self-signed certificates, or when DNS entries (e.g., CNAMEs) don't match certificate hostnames.

  • This setting is typically used in development or testing environments. It is strongly discouraged in production, as it introduces security risks such as man-in-the-middle attacks.

  • Only valid if TLS is already enabled in the base client configuration. Enabling it without TLS will result in a ConfigurationError.

  • Default: False (verification is enforced).

root_pem_cacerts Optional[bytes]

Custom root certificate data for TLS connections in PEM format.

  • When provided, these certificates will be used instead of the system's default trust store. This is useful for connecting to servers with self-signed certificates or corporate certificate authorities.

  • If set to an empty bytes object (non-None but length 0), a ConfigurationError will be raised.

  • If None (default), the system's default certificate trust store will be used (platform verifier).

  • The certificate data should be in PEM format as a bytes object.

  • Multiple certificates can be provided by concatenating them in PEM format.

Example usage::

# Load from file
with open('/path/to/ca-cert.pem', 'rb') as f:
    cert_data = f.read()
tls_config = TlsAdvancedConfiguration(root_pem_cacerts=cert_data)

# Or provide directly
cert_data = b"-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----"
tls_config = TlsAdvancedConfiguration(root_pem_cacerts=cert_data)
client_cert_pem Optional[bytes]

Client certificate data for mutual TLS authentication in PEM format.

  • When provided along with client_key_pem, enables mutual TLS (mTLS) authentication so that the client presents its certificate to the server.

  • This is to be used when the server requires client certificate authentication.

  • If set to an empty bytes object (non-None but length 0), a ConfigurationError will be raised.

  • If None (default), no client certificate will be presented.

  • The certificate data should be in PEM format as a bytes object.

  • Must be used together with client_key_pem.

Example usage::

# Load from file
with open('/path/to/client-cert.pem', 'rb') as f:
    client_cert = f.read()
with open('/path/to/client-key.pem', 'rb') as f:
    client_key = f.read()
tls_config = TlsAdvancedConfiguration(
    client_cert_pem=client_cert,
    client_key_pem=client_key
)
client_key_pem Optional[bytes]

Client private key data for mutual TLS authentication in PEM format.

  • When provided along with client_cert_pem, enables mutual TLS (mTLS) authentication.

  • This private key corresponds to the certificate provided in client_cert_pem.

  • If set to an empty bytes object (non-None but length 0), a ConfigurationError will be raised.

  • If None (default), no client key will be used.

  • The key data should be in PEM format as a bytes object.

  • Must be used together with client_cert_pem.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/config.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
class TlsAdvancedConfiguration:
    """
    Represents advanced TLS configuration settings.

    Attributes:
        use_insecure_tls (Optional[bool]): Whether to bypass TLS certificate verification.

            - When set to True, the client skips certificate validation.
              This is useful when connecting to servers or clusters using self-signed certificates,
              or when DNS entries (e.g., CNAMEs) don't match certificate hostnames.

            - This setting is typically used in development or testing environments. **It is
              strongly discouraged in production**, as it introduces security risks such as man-in-the-middle attacks.

            - Only valid if TLS is already enabled in the base client configuration.
              Enabling it without TLS will result in a `ConfigurationError`.

            - Default: False (verification is enforced).

        root_pem_cacerts (Optional[bytes]): Custom root certificate data for TLS connections in PEM format.

            - When provided, these certificates will be used instead of the system's default trust store.
              This is useful for connecting to servers with self-signed certificates or corporate
              certificate authorities.

            - If set to an empty bytes object (non-None but length 0), a `ConfigurationError` will be raised.

            - If None (default), the system's default certificate trust store will be used (platform verifier).

            - The certificate data should be in PEM format as a bytes object.

            - Multiple certificates can be provided by concatenating them in PEM format.

            Example usage::

                # Load from file
                with open('/path/to/ca-cert.pem', 'rb') as f:
                    cert_data = f.read()
                tls_config = TlsAdvancedConfiguration(root_pem_cacerts=cert_data)

                # Or provide directly
                cert_data = b"-----BEGIN CERTIFICATE-----\\n...\\n-----END CERTIFICATE-----"
                tls_config = TlsAdvancedConfiguration(root_pem_cacerts=cert_data)

        client_cert_pem (Optional[bytes]): Client certificate data for mutual TLS authentication in PEM format.

            - When provided along with client_key_pem, enables mutual TLS (mTLS) authentication
              so that the client presents its certificate to the server.

            - This is to be used when the server requires client certificate authentication.

            - If set to an empty bytes object (non-None but length 0), a `ConfigurationError` will be raised.

            - If None (default), no client certificate will be presented.

            - The certificate data should be in PEM format as a bytes object.

            - Must be used together with client_key_pem.

            Example usage::

                # Load from file
                with open('/path/to/client-cert.pem', 'rb') as f:
                    client_cert = f.read()
                with open('/path/to/client-key.pem', 'rb') as f:
                    client_key = f.read()
                tls_config = TlsAdvancedConfiguration(
                    client_cert_pem=client_cert,
                    client_key_pem=client_key
                )

        client_key_pem (Optional[bytes]): Client private key data for mutual TLS authentication in PEM format.

            - When provided along with client_cert_pem, enables mutual TLS (mTLS) authentication.

            - This private key corresponds to the certificate provided in client_cert_pem.

            - If set to an empty bytes object (non-None but length 0), a `ConfigurationError` will be raised.

            - If None (default), no client key will be used.

            - The key data should be in PEM format as a bytes object.

            - Must be used together with client_cert_pem.
    """

    def __init__(
        self,
        use_insecure_tls: Optional[bool] = None,
        root_pem_cacerts: Optional[bytes] = None,
        client_cert_pem: Optional[bytes] = None,
        client_key_pem: Optional[bytes] = None,
    ):
        self.use_insecure_tls = use_insecure_tls
        self.root_pem_cacerts = root_pem_cacerts
        self.client_cert_pem = client_cert_pem
        self.client_key_pem = client_key_pem

ClosingError

Bases: GlideError

Errors that report that the client has closed and is no longer usable.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
20
21
22
23
24
25
class ClosingError(GlideError):
    """
    Errors that report that the client has closed and is no longer usable.
    """

    pass

ConfigurationError

Bases: RequestError

Errors that are thrown when a request cannot be completed in current configuration settings.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
61
62
63
64
65
66
class ConfigurationError(RequestError):
    """
    Errors that are thrown when a request cannot be completed in current configuration settings.
    """

    pass

ConnectionError

Bases: RequestError

Errors that are thrown when a connection disconnects. These errors can be temporary, as the client will attempt to reconnect.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
52
53
54
55
56
57
58
class ConnectionError(RequestError):
    """
    Errors that are thrown when a connection disconnects.
    These errors can be temporary, as the client will attempt to reconnect.
    """

    pass

ExecAbortError

Bases: RequestError

Errors that are thrown when a transaction is aborted.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
44
45
46
47
48
49
class ExecAbortError(RequestError):
    """
    Errors that are thrown when a transaction is aborted.
    """

    pass

GlideError

Bases: Exception

Base class for errors.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
 8
 9
10
11
12
13
14
15
16
17
class GlideError(Exception):
    """
    Base class for errors.
    """

    def __init__(self, message: Optional[str] = None):
        super().__init__(message or "No error message provided")

    def name(self):
        return self.__class__.__name__

LoggerError

Bases: GlideError

Errors that are thrown when the logger has an error initializing.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
69
70
71
72
73
74
class LoggerError(GlideError):
    """
    Errors that are thrown when the logger has an error initializing.
    """

    pass

RequestError

Bases: GlideError

Errors that were reported during a request.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
28
29
30
31
32
33
class RequestError(GlideError):
    """
    Errors that were reported during a request.
    """

    pass

TimeoutError

Bases: RequestError

Errors that are thrown when a request times out.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/exceptions.py
36
37
38
39
40
41
class TimeoutError(RequestError):
    """
    Errors that are thrown when a request times out.
    """

    pass

OpenTelemetryConfig

Configuration for OpenTelemetry integration.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/opentelemetry.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
class OpenTelemetryConfig:
    """Configuration for OpenTelemetry integration."""

    def __init__(
        self,
        traces: Optional[OpenTelemetryTracesConfig] = None,
        metrics: Optional[OpenTelemetryMetricsConfig] = None,
        flush_interval_ms: Optional[int] = None,
    ) -> None:
        self.traces = traces
        self.metrics = metrics
        self.flush_interval_ms = flush_interval_ms

    def get_traces(self) -> Optional[OpenTelemetryTracesConfig]:
        return self.traces

    def set_traces(self, traces: OpenTelemetryTracesConfig) -> None:
        self.traces = traces

    def get_metrics(self) -> Optional[OpenTelemetryMetricsConfig]:
        return self.metrics

    def get_flush_interval_ms(self) -> Optional[int]:
        return self.flush_interval_ms

OpenTelemetryMetricsConfig

Configuration for exporting OpenTelemetry metrics.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/opentelemetry.py
67
68
69
70
71
72
73
74
class OpenTelemetryMetricsConfig:
    """Configuration for exporting OpenTelemetry metrics."""

    def __init__(self, endpoint: str) -> None:
        self.endpoint = endpoint

    def get_endpoint(self) -> str:
        return self.endpoint

OpenTelemetryTracesConfig

Configuration for exporting OpenTelemetry traces.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/opentelemetry.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class OpenTelemetryTracesConfig:
    """Configuration for exporting OpenTelemetry traces."""

    def __init__(self, endpoint: str, sample_percentage: Optional[int] = None) -> None:
        self.endpoint = endpoint
        self.sample_percentage = (
            sample_percentage if sample_percentage is not None else 1
        )

    def get_endpoint(self) -> str:
        return self.endpoint

    def get_sample_percentage(self) -> int:
        return self.sample_percentage

AllNodes

Bases: Route

Route request to all nodes.

Warning

Don't use it with write commands, they could be routed to a replica (RO) node and fail.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
38
39
40
41
42
43
44
45
46
class AllNodes(Route):
    """
    Route request to all nodes.

    Warning:
        Don't use it with write commands, they could be routed to a replica (RO) node and fail.
    """

    pass

AllPrimaries

Bases: Route

Route request to all primary nodes.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
49
50
51
52
53
54
class AllPrimaries(Route):
    """
    Route request to all primary nodes.
    """

    pass

ByAddressRoute

Bases: Route

Routes a request to a node by its address

Attributes:

Name Type Description
host str

The endpoint of the node. If port is not provided, should be in the f"{address}:{port}" format, where address is the preferred endpoint as shown in the output of the CLUSTER SLOTS command.

port Optional[int]

The port to access on the node. If port is not provided, host is assumed to be in the format f"{address}:{port}".

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class ByAddressRoute(Route):
    """Routes a request to a node by its address

    Attributes:
        host (str): The endpoint of the node. If `port` is not provided, should be in the f"{address}:{port}" format,
            where `address` is the preferred endpoint as shown in the output of the `CLUSTER SLOTS` command.
        port (Optional[int]): The port to access on the node. If port is not provided, `host` is assumed to be in
            the format f"{address}:{port}".
    """

    def __init__(self, host: str, port: Optional[int] = None) -> None:
        super().__init__()
        if port is None:
            split = host.split(":")
            if len(split) < 2:
                raise RequestError(
                    "No port provided, expected host to be formatted as {hostname}:{port}`. Received "
                    + host
                )
            self.host = split[0]
            self.port = int(split[1])
        else:
            self.host = host
            self.port = port

RandomNode

Bases: Route

Route request to a random node.

Warning

Don't use it with write commands, because they could be randomly routed to a replica (RO) node and fail.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
57
58
59
60
61
62
63
64
65
class RandomNode(Route):
    """
    Route request to a random node.

    Warning:
        Don't use it with write commands, because they could be randomly routed to a replica (RO) node and fail.
    """

    pass

SlotIdRoute

Bases: Route

Routes a request to a node by its slot ID

Attributes:

Name Type Description
slot_type SlotType

Defines type of the node being addressed.

slot_id int

Slot number. There are 16384 slots in a Valkey cluster, and each shard manages a slot range. Unless the slot is known, it's better to route using SlotType.PRIMARY

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class SlotIdRoute(Route):
    """Routes a request to a node by its slot ID

    Attributes:
        slot_type (SlotType): Defines type of the node being addressed.
        slot_id (int): Slot number. There are 16384 slots in a Valkey cluster, and each shard
            manages a slot range. Unless the slot is known, it's better to route using
            `SlotType.PRIMARY`
    """

    def __init__(self, slot_type: SlotType, slot_id: int) -> None:
        super().__init__()
        self.slot_type = slot_type
        self.slot_id = slot_id

SlotKeyRoute

Bases: Route

Routes a request to a node by its slot key

Attributes:

Name Type Description
slot_type SlotType

Defines type of the node being addressed.

slot_key str

The request will be sent to nodes managing this key.

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
68
69
70
71
72
73
74
75
76
77
78
79
class SlotKeyRoute(Route):
    """Routes a request to a node by its slot key

    Attributes:
        slot_type (SlotType): Defines type of the node being addressed.
        slot_key (str): The request will be sent to nodes managing this key.
    """

    def __init__(self, slot_type: SlotType, slot_key: str) -> None:
        super().__init__()
        self.slot_type = slot_type
        self.slot_key = slot_key

SlotType

Bases: Enum

Source code in doc-gen/valkey-glide/python/glide-shared/glide_shared/routes.py
15
16
17
18
19
20
21
22
23
24
25
26
27
class SlotType(Enum):
    PRIMARY = 1
    """
    Address a primary node.
    """

    REPLICA = 2
    """
    Address a replica node.

    `REPLICA` overrides the `read_from_replica` configuration. If it's used the request
    will be routed to a replica, even if the strategy is `ALWAYS_FROM_MASTER`.
    """

PRIMARY = 1 class-attribute instance-attribute

Address a primary node.

REPLICA = 2 class-attribute instance-attribute

Address a replica node.

REPLICA overrides the read_from_replica configuration. If it's used the request will be routed to a replica, even if the strategy is ALWAYS_FROM_MASTER.