instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Improve my code by adding docstrings | import os
import httpx
import json
from aisuite.provider import Provider, LLMError
from aisuite.framework import ChatCompletionResponse
from aisuite.framework.message import Message, ChatCompletionMessageToolCall
class FireworksMessageConverter:
@staticmethod
def convert_request(messages):
transformed... | --- +++ @@ -9,6 +9,7 @@ class FireworksMessageConverter:
@staticmethod
def convert_request(messages):
+ """Convert messages to Fireworks format."""
transformed_messages = []
for message in messages:
if isinstance(message, Message):
@@ -21,6 +22,7 @@
@staticmethod
... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/fireworks_provider.py |
Include argument descriptions in docstrings |
import os
import json
from typing import List, Dict, Any, Tuple, Optional
import boto3
import botocore
from aisuite.provider import Provider, LLMError
from aisuite.framework import ChatCompletionResponse
from aisuite.framework.message import Message, CompletionUsage
# pylint: disable=too-few-public-methods
class B... | --- +++ @@ -1,3 +1,4 @@+"""AWS Bedrock provider for the aisuite."""
import os
import json
@@ -13,15 +14,18 @@
# pylint: disable=too-few-public-methods
class BedrockConfig:
+ """Configuration for the AWS Bedrock provider."""
INFERENCE_PARAMETERS = ["maxTokens", "temperature", "topP", "stopSequences"]
... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/aws_provider.py |
Generate documentation strings for clarity | from abc import ABC, abstractmethod
from pathlib import Path
import importlib
import os
import functools
from typing import Union, BinaryIO, Optional
class LLMError(Exception):
def __init__(self, message):
super().__init__(message)
class ASRError(Exception):
def __init__(self, message):
su... | --- +++ @@ -7,12 +7,14 @@
class LLMError(Exception):
+ """Custom exception for LLM errors."""
def __init__(self, message):
super().__init__(message)
class ASRError(Exception):
+ """Custom exception for ASR errors."""
def __init__(self, message):
super().__init__(message)
@... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/provider.py |
Write docstrings for data processing functions |
import os
from mistralai import Mistral
from aisuite.framework import ChatCompletionResponse
from aisuite.provider import Provider, LLMError
from aisuite.providers.message_converter import OpenAICompliantMessageConverter
# Implementation of Mistral provider.
# Mistral's message format is the same as OpenAI's. Just d... | --- +++ @@ -1,3 +1,4 @@+"""Mistral provider for the aisuite."""
import os
from mistralai import Mistral
@@ -14,8 +15,12 @@
class MistralMessageConverter(OpenAICompliantMessageConverter):
+ """
+ Mistral-specific message converter
+ """
def convert_response(self, response_data) -> ChatCompletionR... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/mistral_provider.py |
Add docstrings to make code maintainable | import os
import json
import time
from typing import Union, BinaryIO
import requests
from huggingface_hub import InferenceClient
from aisuite.provider import Provider, LLMError, ASRError, Audio
from aisuite.framework import ChatCompletionResponse
from aisuite.framework.message import Message, TranscriptionResult, Word
... | --- +++ @@ -10,8 +10,19 @@
class HuggingfaceProvider(Provider):
+ """
+ HuggingFace Provider using the official InferenceClient.
+ This provider supports calls to HF serverless Inference Endpoints
+ which use Text Generation Inference (TGI) as the backend.
+ TGI is OpenAI protocol compliant.
+ htt... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/huggingface_provider.py |
Document this script properly |
from typing import Any, Dict, List, Optional, Union, get_args, get_origin
import inspect
def json_schema_to_python_type(schema: Dict[str, Any]) -> type:
schema_type = schema.get("type")
# Handle null/None
if schema_type == "null":
return type(None)
# Handle basic types
type_mapping = {
... | --- +++ @@ -1,9 +1,24 @@+"""
+Schema conversion utilities for MCP tools.
+
+This module provides functionality to convert MCP JSON Schema tool definitions
+to Python type annotations that are compatible with aisuite's existing Tools class.
+"""
from typing import Any, Dict, List, Optional, Union, get_args, get_origi... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/mcp/schema_converter.py |
Add minimal docstrings for each function |
# TODO(rohit): Remove this. This interface is obsolete in favor of Provider.
class ProviderInterface:
def chat_completion_create(self, messages=None, model=None, temperature=0) -> None:
raise NotImplementedError(
"Provider Interface has not implemented chat_completion_create()"
) | --- +++ @@ -1,9 +1,26 @@+"""The shared interface for model providers."""
# TODO(rohit): Remove this. This interface is obsolete in favor of Provider.
class ProviderInterface:
+ """Defines the expected behavior for provider-specific interfaces."""
def chat_completion_create(self, messages=None, model=Non... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/framework/provider_interface.py |
Create docstrings for all classes and functions | import os
import json
import numpy as np
import queue
import threading
import time
from typing import Union, BinaryIO, AsyncGenerator
from aisuite.provider import Provider, ASRError, Audio
from aisuite.framework.message import (
TranscriptionResult,
Segment,
Word,
Alternative,
Channel,
Streamin... | --- +++ @@ -18,8 +18,10 @@
class DeepgramProvider(Provider):
+ """Deepgram ASR provider."""
def __init__(self, **config):
+ """Initialize the Deepgram provider with the given configuration."""
super().__init__()
# Ensure API key is provided either in config or via environment va... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/deepgram_provider.py |
Help me add docstrings to my project |
from typing import Dict, Any, List, TYPE_CHECKING
if TYPE_CHECKING:
from .message import TranscriptionOptions
class ParameterMapper:
# OpenAI Whisper API parameter mapping
OPENAI_MAPPING = {
"language": "language",
"response_format": "response_format",
"temperature": "temperatur... | --- +++ @@ -1,3 +1,7 @@+"""
+Parameter mapping utilities for ASR providers.
+Maps unified TranscriptionOptions to provider-specific parameters.
+"""
from typing import Dict, Any, List, TYPE_CHECKING
@@ -6,6 +10,7 @@
class ParameterMapper:
+ """Maps unified TranscriptionOptions to provider-specific parameter... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/framework/parameter_mapper.py |
Create simple docstrings for beginners | from .provider import ProviderFactory
import os
from .utils.tools import Tools
from typing import Union, BinaryIO, Optional, Any, Literal
from contextlib import ExitStack
from .framework.message import (
TranscriptionResponse,
)
from .framework.asr_params import ParamValidator
# Import MCP utilities for config dic... | --- +++ @@ -24,6 +24,28 @@ provider_configs: dict = {},
extra_param_mode: Literal["strict", "warn", "permissive"] = "warn",
):
+ """
+ Initialize the client with provider configurations.
+ Use the ProviderFactory to create provider instances.
+
+ Args:
+ prov... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/client.py |
Generate helpful docstrings for debugging |
from typing import Optional
from aisuite.framework.choice import Choice
from aisuite.framework.message import CompletionUsage
# pylint: disable=too-few-public-methods
class ChatCompletionResponse:
def __init__(self):
self.choices = [Choice()] # Adjust the range as needed for more choices
self.... | --- +++ @@ -1,3 +1,4 @@+"""Defines the ChatCompletionResponse class."""
from typing import Optional
@@ -7,7 +8,9 @@
# pylint: disable=too-few-public-methods
class ChatCompletionResponse:
+ """Used to conform to the response model of OpenAI."""
def __init__(self):
+ """Initializes the ChatComple... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/framework/chat_completion_response.py |
Add return value explanations in docstrings | from typing import Callable, Dict, Any, Type, Optional, get_origin, get_args, Union
from pydantic import BaseModel, create_model, Field, ValidationError
import inspect
import json
from docstring_parser import parse
class Tools:
def __init__(self, tools: list[Callable] = None):
self._tools = {}
if ... | --- +++ @@ -14,6 +14,7 @@
# Add a tool function with or without a Pydantic model.
def _add_tool(self, func: Callable, param_model: Optional[Type[BaseModel]] = None):
+ """Register a tool function with metadata. If no param_model is provided, infer from function signature."""
# Check if this i... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/utils/tools.py |
Document all public functions with docstrings |
from aisuite.framework import ChatCompletionResponse
from aisuite.framework.message import (
Message,
ChatCompletionMessageToolCall,
CompletionUsage,
)
class OpenAICompliantMessageConverter:
# Class variable that derived classes can override
tool_results_as_strings = False
@staticmethod
... | --- +++ @@ -1,3 +1,4 @@+"""Base message converter for OpenAI-compliant providers."""
from aisuite.framework import ChatCompletionResponse
from aisuite.framework.message import (
@@ -8,12 +9,16 @@
class OpenAICompliantMessageConverter:
+ """
+ Base class for message converters that are compatible with Open... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/message_converter.py |
Help me comply with documentation standards |
import cerebras.cloud.sdk as cerebras
from aisuite.provider import Provider, LLMError
from aisuite.providers.message_converter import OpenAICompliantMessageConverter
class CerebrasMessageConverter(OpenAICompliantMessageConverter):
# pylint: disable=too-few-public-methods
class CerebrasProvider(Provider):
def ... | --- +++ @@ -1,3 +1,4 @@+"""Cerebras provider for the aisuite."""
import cerebras.cloud.sdk as cerebras
from aisuite.provider import Provider, LLMError
@@ -5,16 +6,23 @@
class CerebrasMessageConverter(OpenAICompliantMessageConverter):
+ """
+ Cerebras-specific message converter if needed.
+ """
# p... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/cerebras_provider.py |
Write docstrings for utility functions | import os
import groq
from aisuite.provider import Provider, LLMError
from aisuite.providers.message_converter import OpenAICompliantMessageConverter
# Implementation of Groq provider.
# Groq's message format is same as OpenAI's.
# Tool calling specification is also exactly the same as OpenAI's.
# Links:
# https://con... | --- +++ @@ -21,12 +21,19 @@
class GroqMessageConverter(OpenAICompliantMessageConverter):
+ """
+ Groq-specific message converter if needed
+ """
pass
class GroqProvider(Provider):
def __init__(self, **config):
+ """
+ Initialize the Groq provider with the given configuration.... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/groq_provider.py |
Add docstrings that explain logic | import os
import httpx
from aisuite.provider import Provider, LLMError
from aisuite.framework import ChatCompletionResponse
class OllamaProvider(Provider):
_CHAT_COMPLETION_ENDPOINT = "/api/chat"
_CONNECT_ERROR_MESSAGE = "Ollama is likely not running. Start Ollama by running `ollama serve` on your host."
... | --- +++ @@ -5,11 +5,20 @@
class OllamaProvider(Provider):
+ """
+ Ollama Provider that makes HTTP calls instead of using SDK.
+ It uses the /api/chat endpoint.
+ Read more here - https://github.com/ollama/ollama/blob/main/docs/api.md#generate-a-chat-completion
+ If OLLAMA_API_URL is not set and not p... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/ollama_provider.py |
Add minimal docstrings for each function | import openai
import os
from typing import Union, BinaryIO, AsyncGenerator
from aisuite.provider import Provider, LLMError, ASRError, Audio
from aisuite.providers.message_converter import OpenAICompliantMessageConverter
from aisuite.framework.message import (
TranscriptionResult,
Segment,
Word,
Streamin... | --- +++ @@ -13,6 +13,10 @@
class OpenaiProvider(Provider):
def __init__(self, **config):
+ """
+ Initialize the OpenAI provider with the given configuration.
+ Pass the entire configuration dictionary to the OpenAI client constructor.
+ """
# Ensure API key is provided either... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/openai_provider.py |
Create documentation for each function signature | import urllib.request
import json
import os
from aisuite.provider import Provider
from aisuite.framework import ChatCompletionResponse
from aisuite.framework.message import Message, ChatCompletionMessageToolCall, Function
# Azure provider is based on the documentation here -
# https://learn.microsoft.com/en-us/azure/... | --- +++ @@ -40,6 +40,7 @@ class AzureMessageConverter:
@staticmethod
def convert_request(messages):
+ """Convert messages to Azure format."""
transformed_messages = []
for message in messages:
if isinstance(message, Message):
@@ -50,6 +51,7 @@
@staticmethod
def... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/azure_provider.py |
Generate consistent docstrings | import os
import httpx
from aisuite.provider import Provider, LLMError
from aisuite.framework import ChatCompletionResponse
from aisuite.providers.message_converter import OpenAICompliantMessageConverter
class XaiMessageConverter(OpenAICompliantMessageConverter):
pass
class XaiProvider(Provider):
BASE_URL... | --- +++ @@ -6,15 +6,25 @@
class XaiMessageConverter(OpenAICompliantMessageConverter):
+ """
+ xAI-specific message converter if needed
+ """
pass
class XaiProvider(Provider):
+ """
+ xAI Provider using httpx for direct API calls.
+ """
BASE_URL = "https://api.x.ai/v1/chat/comple... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/providers/xai_provider.py |
Improve documentation using docstrings |
from typing import Dict, Set, Any, Optional, Literal
import logging
logger = logging.getLogger(__name__)
# Common parameters that get auto-mapped across providers
# These follow OpenAI's API conventions for maximum portability
COMMON_PARAMS: Dict[str, Dict[str, Optional[str]]] = {
"language": {
"openai"... | --- +++ @@ -1,3 +1,12 @@+"""
+ASR parameter registry and validation.
+
+This module provides a unified parameter validation system for audio transcription
+across different providers. It supports:
+- Common parameters (OpenAI-style) that are auto-mapped to provider equivalents
+- Provider-specific parameters that are p... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/framework/asr_params.py |
Add docstrings for internal functions |
from typing import Any, Callable, Dict, Optional
import asyncio
import inspect
from .schema_converter import (
mcp_schema_to_annotations,
extract_parameter_descriptions,
build_docstring,
)
class MCPToolWrapper:
def __init__(
self,
mcp_client: "MCPClient", # Forward reference to avoi... | --- +++ @@ -1,3 +1,10 @@+"""
+MCP Tool Wrapper for aisuite.
+
+This module provides the MCPToolWrapper class, which creates Python callable
+wrappers around MCP tools that are compatible with aisuite's existing tool
+calling infrastructure.
+"""
from typing import Any, Callable, Dict, Optional
import asyncio
@@ -10... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/mcp/tool_wrapper.py |
Create Google-style docstrings for my code |
import json
from unittest.mock import MagicMock
from pydantic import BaseModel
# pylint: disable=too-few-public-methods
class Utils:
@staticmethod
def spew(obj):
visited = set()
# pylint: disable=too-many-return-statements
def default_encoder(o):
# Handle MagicMock objec... | --- +++ @@ -1,3 +1,4 @@+"""Utility functions for aisuite."""
import json
from unittest.mock import MagicMock
@@ -6,9 +7,17 @@
# pylint: disable=too-few-public-methods
class Utils:
+ """
+ Utility functions for debugging and inspecting objects.
+ """
@staticmethod
def spew(obj):
+ """
... | https://raw.githubusercontent.com/andrewyng/aisuite/HEAD/aisuite/utils/utils.py |
Fully document this Python code with docstrings | # -*- coding: utf-8 -*-
import random
import bisect
def weighted_choice(choices):
values, weights = zip(*choices)
total = 0
cum_weights = []
for w in weights:
total += w
cum_weights.append(total)
x = random.uniform(0, total)
i = bisect.bisect(cum_weights, x)
return values... | --- +++ @@ -1,11 +1,24 @@ # -*- coding: utf-8 -*-
+"""
+httpbin.utils
+~~~~~~~~~~~~~~~
+
+Utility functions.
+"""
import random
import bisect
def weighted_choice(choices):
+ """Returns a value from choices chosen by weighted random selection
+
+ choices should be a list of (value, weight) tuples.
+
+ ... | https://raw.githubusercontent.com/postmanlabs/httpbin/HEAD/httpbin/utils.py |
Write docstrings describing each step | # -*- coding: utf-8 -*-
import base64
import json
import os
import random
import time
import uuid
import argparse
from flask import (
Flask,
Response,
request,
render_template,
redirect,
jsonify as flask_jsonify,
make_response,
url_for,
abort,
)
from six.moves import range as xran... | --- +++ @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*-
+"""
+httpbin.core
+~~~~~~~~~~~~
+
+This module provides the core HttpBin experience.
+"""
import base64
import json
@@ -233,17 +239,38 @@
@app.route("/legacy")
def view_landing_page():
+ """Generates Landing Page in legacy layout."""
return render_templ... | https://raw.githubusercontent.com/postmanlabs/httpbin/HEAD/httpbin/core.py |
Annotate my code with docstrings | # -*- coding: utf-8 -*-
import gzip as gzip2
import zlib
import brotli as _brotli
from six import BytesIO
from decimal import Decimal
from time import time as now
from decorator import decorator
from flask import Flask, Response
app = Flask(__name__)
@decorator
def x_runtime(f, *args, **kwargs):
_t0 = now... | --- +++ @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*-
+"""
+httpbin.filters
+~~~~~~~~~~~~~~~
+
+This module provides response filter decorators.
+"""
import gzip as gzip2
import zlib
@@ -19,6 +25,7 @@
@decorator
def x_runtime(f, *args, **kwargs):
+ """X-Runtime Flask Response Decorator."""
_t0 = now()
... | https://raw.githubusercontent.com/postmanlabs/httpbin/HEAD/httpbin/filters.py |
Can you add docstrings to this Python file? | # -*- coding: utf-8 -*-
import json
import base64
import re
import time
import os
from hashlib import md5, sha256, sha512
from werkzeug.http import parse_authorization_header
from werkzeug.datastructures import WWWAuthenticate
from flask import request, make_response
from six.moves.urllib.parse import urlparse, urlu... | --- +++ @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*-
+"""
+httpbin.helpers
+~~~~~~~~~~~~~~~
+
+This module provides helper functions for httpbin.
+"""
import json
import base64
@@ -77,6 +83,16 @@
def json_safe(string, content_type='application/octet-stream'):
+ """Returns JSON-safe version of `string`.
+
+ ... | https://raw.githubusercontent.com/postmanlabs/httpbin/HEAD/httpbin/helpers.py |
Include argument descriptions in docstrings | # -*- coding: utf-8 -*-
class CaseInsensitiveDict(dict):
def _lower_keys(self):
return [k.lower() for k in self.keys()]
def __contains__(self, key):
return key.lower() in self._lower_keys()
def __getitem__(self, key):
# We allow fall-through here, so values default to None
... | --- +++ @@ -1,8 +1,19 @@ # -*- coding: utf-8 -*-
+"""
+httpbin.structures
+~~~~~~~~~~~~~~~~~~~
+
+Data structures that power httpbin.
+"""
class CaseInsensitiveDict(dict):
+ """Case-insensitive Dictionary for headers.
+
+ For example, ``headers['content-encoding']`` will return the
+ value of a ``'Conte... | https://raw.githubusercontent.com/postmanlabs/httpbin/HEAD/httpbin/structures.py |
Document helper functions with docstrings | import logging
from collections import OrderedDict
from typing import Dict, List, Optional, Tuple, Union
import torch
import torch.nn as nn
try:
import timm
from timm.layers import RotAttentionPool2d
from timm.layers import AttentionPool2d as AbsAttentionPool2d
from timm.layers import Mlp, to_2tuple
e... | --- +++ @@ -1,3 +1,7 @@+""" timm model adapter
+
+Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model.
+"""
import logging
from collections import OrderedDict
from typing import Dict, List, Optional, Tuple, Union
@@ -17,6 +21,8 @@
class TimmModel(nn.Modul... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/timm_model.py |
Provide docstrings following PEP 257 | from functools import partial
from itertools import islice
from typing import Callable, List, Optional, Sequence, Union
import torch
import torch.nn.functional as F
def batched(iterable, n):
it = iter(iterable)
while True:
batch = list(islice(it, n))
if not batch:
break
yi... | --- +++ @@ -7,6 +7,9 @@
def batched(iterable, n):
+ """Batch data into lists of length *n*. The last batch may be shorter.
+ NOTE based on more-itertools impl, to be replaced by python 3.12 itertools.batched impl
+ """
it = iter(iterable)
while True:
batch = list(islice(it, n))
@@ -24,6 ... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/zero_shot_classifier.py |
Add docstrings including usage examples | import ast
import json
import logging
import math
import os
import random
import sys
import braceexpand
from dataclasses import dataclass
from multiprocessing import Value
import numpy as np
import pandas as pd
import torch
import torchvision.datasets as datasets
import webdataset as wds
from PIL import Image
from tor... | --- +++ @@ -178,11 +178,17 @@
def log_and_continue(exn):
+ """Call in an exception handler to ignore any exception, issue a warning, and continue."""
logging.warning(f'Handling webdataset error ({repr(exn)}). Ignoring.')
return True
def group_by_keys_nothrow(data, keys=base_plus_ext, lcase=True, s... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip_train/data.py |
Generate helpful docstrings for debugging | import re
import torch
import torch.nn as nn
from torch import TensorType
try:
import transformers
from transformers import AutoModel, AutoTokenizer, AutoConfig, PretrainedConfig
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, \
BaseModelOutputWithPoolingAndC... | --- +++ @@ -1,3 +1,7 @@+""" huggingface model adapter
+
+Wraps HuggingFace transformers (https://github.com/huggingface/transformers) models for use as a text tower in CLIP model.
+"""
import re
import torch
@@ -33,12 +37,14 @@
def register_pooler(cls):
+ """Decorator registering pooler class"""
_POOLER... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/hf_model.py |
Generate docstrings with parameter types | import gzip
import html
import os
import random
import string
from functools import lru_cache, partial
from typing import Callable, List, Optional, Union, Dict
import warnings
import ftfy
import numpy as np
import regex as re
import torch
# https://stackoverflow.com/q/62691279
os.environ["TOKENIZERS_PARALLELISM"] = "... | --- +++ @@ -1,3 +1,7 @@+""" CLIP tokenizer
+
+Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
+"""
import gzip
import html
import os
@@ -26,6 +30,15 @@
@lru_cache()
def bytes_to_unicode():
+ """
+ Returns list of utf-8 byte and a corresponding list of unicode s... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/tokenizer.py |
Generate missing documentation strings | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
# Position embedding utils
# -----------------------------------... | --- +++ @@ -18,6 +18,11 @@ # MoCo v3: https://github.com/facebookresearch/moco-v3
# --------------------------------------------------------
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
+ """
+ grid_size: int of the grid height and width
+ return:
+ pos_embed: [grid_size*grid_size, ... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/pos_embed.py |
Add docstrings to make code maintainable | import copy
import logging
import math
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils.checkpoint import checkpoint
from functools import partial
from .hf_model import HFT... | --- +++ @@ -1,3 +1,7 @@+""" CLIP Model
+
+Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
+"""
import copy
import logging
import math
@@ -366,6 +370,26 @@ output_logits: bool = False,
output_logit_scale_bias: bool = False,
) -> Dict[str, U... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/model.py |
Add professional docstrings to my codebase | from collections import OrderedDict
from typing import Dict, List, Optional, Union
import torch
from torch import nn
from torch.nn import functional as F
from .utils import freeze_batch_norm_2d, feature_take_indices
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
... | --- +++ @@ -94,6 +94,12 @@
class ModifiedResNet(nn.Module):
+ """
+ A ResNet class that is similar to torchvision's but contains the following changes:
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
+ - Performs antialiasing strided convolutions, whe... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/modified_resnet.py |
Create structured documentation for my script |
import os
import warnings
from typing import List, Optional, Union
import torch
from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
from .model import build_model_from_openai_state_dict, convert_weights_to_lp, get_cast_dtype
from .pretrained import get_pretrained_url, list_pretrained_models_by_tag, downlo... | --- +++ @@ -1,3 +1,7 @@+""" OpenAI pretrained model functions
+
+Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
+"""
import os
import warnings
@@ -13,6 +17,7 @@
def list_openai_models() -> List[str]:
+ """Returns the names of available CLIP models"""
retu... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/openai.py |
Generate docstrings with examples | import json
import logging
import os
import re
import warnings
from copy import deepcopy
from dataclasses import asdict
from pathlib import Path
from typing import Any, Dict, Optional, Tuple, Union
import torch
from .convert import convert_state_dict
from .model import CLIP, CustomTextCLIP, convert_weights_to_lp, con... | --- +++ @@ -54,10 +54,12 @@
def list_models():
+ """ enumerate available model architectures based on config files """
return list(_MODEL_CONFIGS.keys())
def add_model_config(path):
+ """ add model config path or file and update registry """
if not isinstance(path, Path):
path = Path(p... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/factory.py |
Add docstrings with type hints explained | import collections.abc
from itertools import repeat
from typing import List, Optional, Tuple, Union
import torch
from torch import nn as nn
from torch import _assert
from torchvision.ops.misc import FrozenBatchNorm2d
def freeze_batch_norm_2d(module, module_match={}, name=''):
res = module
is_match = True
... | --- +++ @@ -9,6 +9,21 @@
def freeze_batch_norm_2d(module, module_match={}, name=''):
+ """
+ Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is
+ itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNo... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/utils.py |
Expand my code with proper documentation strings | import copy
import hashlib
import os
import urllib
import warnings
from functools import partial
from typing import Dict, Iterable, Optional, Union
from tqdm import tqdm
try:
import safetensors.torch
_has_safetensors = True
except ImportError:
_has_safetensors = False
from .constants import (
IMAGE... | --- +++ @@ -745,10 +745,14 @@
def list_pretrained(as_str: bool = False):
+ """ returns list of pretrained models
+ Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True
+ """
return [':'.join([k, t]) if as_str else (k, t) for k in _PRETRAINED.keys() for t in _PRETRAINED... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/pretrained.py |
Add docstrings to improve readability | from collections import OrderedDict
import math
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Type, Union
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.checkpoint import checkpoint
from .utils import to_2tuple, feature_take_indices
from .pos_embed import... | --- +++ @@ -12,6 +12,7 @@
class LayerNormFp32(nn.LayerNorm):
+ """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back)."""
def forward(self, x: torch.Tensor):
orig_type = x.dtype
@@ -20,6 +21,7 @@
class LayerNorm(nn.LayerNorm):
+ """Subclass torch's LayerNorm (with ca... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/transformer.py |
Generate descriptive docstrings automatically | from typing import Union
import torch
import numpy as np
from .model import CLIP, CustomTextCLIP
from .transformer import TextTransformer, Transformer
@torch.no_grad()
def load_big_vision_weights(model: CustomTextCLIP, checkpoint_path: str):
from timm.layers import resample_patch_embed, resample_abs_pos_embed
... | --- +++ @@ -1,3 +1,5 @@+""" Conversion functions for 3rd part state-dicts and non-torch native checkpoint formats.
+"""
from typing import Union
import torch
@@ -9,6 +11,11 @@
@torch.no_grad()
def load_big_vision_weights(model: CustomTextCLIP, checkpoint_path: str):
+ """ Load weights from .npz checkpoints fo... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/convert.py |
Add docstrings for internal functions | import numbers
import random
import warnings
from dataclasses import dataclass, asdict
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import numpy as np
import torch
import torchvision.transforms.functional as F
from torchvision.transforms import Normalize, Compose, RandomResizedCrop, Interpolati... | --- +++ @@ -42,6 +42,9 @@ base: Union[PreprocessCfg, Dict],
overlay: Dict,
):
+ """ Merge overlay key-value pairs on top of base preprocess cfg or dict.
+ Input dicts are filtered based on PreprocessCfg fields.
+ """
if isinstance(base, PreprocessCfg):
base_clean = asdict(base)
... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip/transform.py |
Add detailed docstrings explaining each function | import argparse
import torch
import open_clip
import pandas as pd
from torch.utils.flop_counter import FlopCounterMode
try:
import fvcore
import fvcore.nn
except:
fvcore = None
parser = argparse.ArgumentParser(description='OpenCLIP Profiler')
# benchmark specific args
parser.add_argument('--model', metav... | --- +++ @@ -83,6 +83,7 @@
def profile_torch_image(model, image_input_size, batch_size=1, force_cpu=False):
+ """Profile the image encoder using torch.utils.flop_counter"""
if force_cpu:
model = model.to('cpu')
device, dtype = next(model.parameters()).device, next(model.parameters()).dtype
@@ -... | https://raw.githubusercontent.com/mlfoundations/open_clip/HEAD/src/open_clip_train/profiler.py |
Create Google-style docstrings for my code |
class SkillError(Exception):
pass
class ParseError(SkillError):
pass
class ValidationError(SkillError):
def __init__(self, message: str, errors: list[str] | None = None):
super().__init__(message)
self.errors = errors if errors is not None else [message] | --- +++ @@ -1,17 +1,25 @@+"""Skill-related exceptions."""
class SkillError(Exception):
+ """Base exception for all skill-related errors."""
pass
class ParseError(SkillError):
+ """Raised when SKILL.md parsing fails."""
pass
class ValidationError(SkillError):
+ """Raised when skill ... | https://raw.githubusercontent.com/agentskills/agentskills/HEAD/skills-ref/src/skills_ref/errors.py |
Document this script properly |
from pathlib import Path
from typing import Optional
import strictyaml
from .errors import ParseError, ValidationError
from .models import SkillProperties
def find_skill_md(skill_dir: Path) -> Optional[Path]:
for name in ("SKILL.md", "skill.md"):
path = skill_dir / name
if path.exists():
... | --- +++ @@ -1,3 +1,4 @@+"""YAML frontmatter parsing for SKILL.md files."""
from pathlib import Path
from typing import Optional
@@ -9,6 +10,16 @@
def find_skill_md(skill_dir: Path) -> Optional[Path]:
+ """Find the SKILL.md file in a skill directory.
+
+ Prefers SKILL.md (uppercase) but accepts skill.md (l... | https://raw.githubusercontent.com/agentskills/agentskills/HEAD/skills-ref/src/skills_ref/parser.py |
Document all public functions with docstrings |
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class SkillProperties:
name: str
description: str
license: Optional[str] = None
compatibility: Optional[str] = None
allowed_tools: Optional[str] = None
metadata: dict[str, str] = field(default_factory=dict)
... | --- +++ @@ -1,3 +1,4 @@+"""Data models for Agent Skills."""
from dataclasses import dataclass, field
from typing import Optional
@@ -5,6 +6,17 @@
@dataclass
class SkillProperties:
+ """Properties parsed from a skill's SKILL.md frontmatter.
+
+ Attributes:
+ name: Skill name in kebab-case (required)
... | https://raw.githubusercontent.com/agentskills/agentskills/HEAD/skills-ref/src/skills_ref/models.py |
Create structured documentation for my script |
import html
from pathlib import Path
from .parser import find_skill_md, read_properties
def to_prompt(skill_dirs: list[Path]) -> str:
if not skill_dirs:
return "<available_skills>\n</available_skills>"
lines = ["<available_skills>"]
for skill_dir in skill_dirs:
skill_dir = Path(skill_d... | --- +++ @@ -1,3 +1,4 @@+"""Generate <available_skills> XML prompt block for agent system prompts."""
import html
from pathlib import Path
@@ -6,6 +7,28 @@
def to_prompt(skill_dirs: list[Path]) -> str:
+ """Generate the <available_skills> XML block for inclusion in agent prompts.
+
+ This XML format is wha... | https://raw.githubusercontent.com/agentskills/agentskills/HEAD/skills-ref/src/skills_ref/prompt.py |
Can you add docstrings to this Python file? |
import json
import sys
from pathlib import Path
import click
from .errors import SkillError
from .parser import read_properties
from .prompt import to_prompt
from .validator import validate
def _is_skill_md_file(path: Path) -> bool:
return path.is_file() and path.name.lower() == "skill.md"
@click.group()
@cl... | --- +++ @@ -1,3 +1,4 @@+"""CLI for skills-ref library."""
import json
import sys
@@ -12,18 +13,29 @@
def _is_skill_md_file(path: Path) -> bool:
+ """Check if path points directly to a SKILL.md or skill.md file."""
return path.is_file() and path.name.lower() == "skill.md"
@click.group()
@click.vers... | https://raw.githubusercontent.com/agentskills/agentskills/HEAD/skills-ref/src/skills_ref/cli.py |
Generate descriptive docstrings automatically |
import unicodedata
from pathlib import Path
from typing import Optional
from .errors import ParseError
from .parser import find_skill_md, parse_frontmatter
MAX_SKILL_NAME_LENGTH = 64
MAX_DESCRIPTION_LENGTH = 1024
MAX_COMPATIBILITY_LENGTH = 500
# Allowed frontmatter fields per Agent Skills Spec
ALLOWED_FIELDS = {
... | --- +++ @@ -1,3 +1,4 @@+"""Skill validation logic."""
import unicodedata
from pathlib import Path
@@ -22,6 +23,11 @@
def _validate_name(name: str, skill_dir: Path) -> list[str]:
+ """Validate skill name format and directory match.
+
+ Skill names support i18n characters (Unicode letters) plus hyphens.
+ ... | https://raw.githubusercontent.com/agentskills/agentskills/HEAD/skills-ref/src/skills_ref/validator.py |
Add docstrings following best practices | from abc import ABC, abstractmethod
from collections import OrderedDict
from dataclasses import dataclass
from enum import Enum
from typing import Any, List, Optional, Union
from redis.observability.attributes import CSCReason
class CacheEntryStatus(Enum):
VALID = "VALID"
IN_PROGRESS = "IN_PROGRESS"
class ... | --- +++ @@ -19,6 +19,17 @@
@dataclass(frozen=True)
class CacheKey:
+ """
+ Represents a unique key for a cache entry.
+
+ Attributes:
+ command (str): The Redis command being cached.
+ redis_keys (tuple): The Redis keys involved in the command.
+ redis_args (tuple): Additional arguments... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/cache.py |
Write docstrings for this repository | from base import Benchmark
from redis.connection import SYM_CRLF, SYM_DOLLAR, SYM_EMPTY, SYM_STAR, Connection
class StringJoiningConnection(Connection):
def send_packed_command(self, command, check_health=True):
if not self._sock:
self.connect()
try:
self._sock.sendall(com... | --- +++ @@ -5,6 +5,7 @@
class StringJoiningConnection(Connection):
def send_packed_command(self, command, check_health=True):
+ "Send an already packed command to the Redis server"
if not self._sock:
self.connect()
try:
@@ -21,6 +22,7 @@ raise
def pack_com... | https://raw.githubusercontent.com/redis/redis-py/HEAD/benchmarks/command_packer_benchmark.py |
Add standardized docstrings across the file | from typing import List, Optional, Tuple, Union
from redis.commands.search.dialect import DEFAULT_DIALECT
class Query:
def __init__(self, query_string: str) -> None:
self._query_string: str = query_string
self._offset: int = 0
self._num: int = 10
self._no_content: bool = False
... | --- +++ @@ -4,8 +4,21 @@
class Query:
+ """
+ Query is used to build complex queries that have more parameters than just
+ the query string. The query string is set in the constructor, and other
+ options have setter functions.
+
+ The setter functions return the query object so they can be chained.
... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/query.py |
Add detailed documentation for each class | from typing import List
from redis.asyncio import Redis
from redis.asyncio.multidb.database import AsyncDatabase
from redis.asyncio.multidb.failure_detector import AsyncFailureDetector
from redis.event import AsyncEventListenerInterface, AsyncOnCommandsFailEvent
class AsyncActiveDatabaseChanged:
def __init__(
... | --- +++ @@ -7,6 +7,9 @@
class AsyncActiveDatabaseChanged:
+ """
+ Event fired when an async active database has been changed.
+ """
def __init__(
self,
@@ -38,6 +41,9 @@
class ResubscribeOnActiveDatabaseChanged(AsyncEventListenerInterface):
+ """
+ Re-subscribe the currently activ... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/multidb/event.py |
Write documentation strings for class attributes | from typing import Dict, List, Optional, Tuple, Union
from redis.exceptions import DataError
from redis.typing import KeyT, Number
ADD_CMD = "TS.ADD"
ALTER_CMD = "TS.ALTER"
CREATERULE_CMD = "TS.CREATERULE"
CREATE_CMD = "TS.CREATE"
DECRBY_CMD = "TS.DECRBY"
DELETERULE_CMD = "TS.DELETERULE"
DEL_CMD = "TS.DEL"
GET_CMD = ... | --- +++ @@ -23,6 +23,7 @@
class TimeSeriesCommands:
+ """RedisTimeSeries Commands."""
def create(
self,
@@ -35,6 +36,55 @@ ignore_max_time_diff: Optional[int] = None,
ignore_max_val_diff: Optional[Number] = None,
):
+ """
+ Create a new time-series.
+
+ ... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/timeseries/commands.py |
Include argument descriptions in docstrings | import itertools
import time
from typing import Any, Dict, List, Optional, Union
from redis._parsers.helpers import pairs_to_dict
from redis.client import NEVER_DECODE, Pipeline
from redis.commands.search.hybrid_query import (
CombineResultsMethod,
HybridCursorQuery,
HybridPostProcessingConfig,
HybridQ... | --- +++ @@ -75,6 +75,7 @@
class SearchCommands:
+ """Search commands."""
def _parse_results(self, cmd, res, **kwargs):
if get_protocol_version(self.client) in ["3", 3]:
@@ -180,6 +181,9 @@ return {res[i]: res[i + 1] for i in range(0, len(res), 2)}
def batch_indexer(self, chunk_size... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/commands.py |
Add documentation for all methods | import asyncio
import copy
import enum
import inspect
import socket
import sys
import time
import warnings
import weakref
from abc import abstractmethod
from itertools import chain
from types import MappingProxyType
from typing import (
Any,
Callable,
Iterable,
List,
Mapping,
Optional,
Proto... | --- +++ @@ -123,6 +123,7 @@
class AbstractConnection:
+ """Manages communication to and from a Redis server"""
__slots__ = (
"db",
@@ -185,6 +186,20 @@ protocol: Optional[int] = 2,
event_dispatcher: Optional[EventDispatcher] = None,
):
+ """
+ Initialize a new ... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/connection.py |
Generate helpful docstrings for debugging | from abc import ABC, abstractmethod
from typing import Optional
from redis._parsers.commands import (
CommandPolicies,
CommandsParser,
PolicyRecords,
RequestPolicy,
ResponsePolicy,
)
STATIC_POLICIES: PolicyRecords = {
"ft": {
"explaincli": CommandPolicies(
request_policy=Re... | --- +++ @@ -124,24 +124,63 @@ class PolicyResolver(ABC):
@abstractmethod
def resolve(self, command_name: str) -> Optional[CommandPolicies]:
+ """
+ Resolves the command name and determines the associated command policies.
+
+ Args:
+ command_name: The name of the command to res... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/policies.py |
Improve my code by adding docstrings | from ..helpers import nativestr
from .utils import list_to_dict
class TSInfo:
rules = []
labels = []
sourceKey = None
chunk_count = None
memory_usage = None
total_samples = None
retention_msecs = None
last_time_stamp = None
first_time_stamp = None
max_samples_per_chunk = None... | --- +++ @@ -3,6 +3,11 @@
class TSInfo:
+ """
+ Hold information and statistics on the time-series.
+ Can be created using ``tsinfo`` command
+ https://redis.io/docs/latest/commands/ts.info/
+ """
rules = []
labels = []
@@ -19,6 +24,41 @@ duplicate_policy = None
def __init__(sel... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/timeseries/info.py |
Turn comments into proper docstrings | import json
from redis._parsers.helpers import pairs_to_dict
from redis.commands.vectorset.commands import CallbacksOptions
def parse_vemb_result(response, **options):
if response is None:
return response
if options.get(CallbacksOptions.RAW.value):
result = {}
result["quantization"] ... | --- +++ @@ -5,6 +5,14 @@
def parse_vemb_result(response, **options):
+ """
+ Handle VEMB result since the command can returning different result
+ structures depending on input options and on quantization type of the vector set.
+
+ Parsing VEMB result into:
+ - List[Union[bytes, Union[int, float]]]
... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/vectorset/utils.py |
Document this code for team use | from abc import abstractmethod
from asyncio import iscoroutinefunction
from datetime import datetime
from typing import Any, Awaitable, Callable, List, Optional, Union
from redis.asyncio import RedisCluster
from redis.asyncio.client import Pipeline, PubSub
from redis.asyncio.multidb.database import AsyncDatabase, Data... | --- +++ @@ -34,72 +34,92 @@ @property
@abstractmethod
def databases(self) -> Databases:
+ """Returns a list of databases."""
pass
@property
@abstractmethod
def failure_detectors(self) -> List[AsyncFailureDetector]:
+ """Returns a list of failure detectors."""
... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/multidb/command_executor.py |
Add clean documentation to messy code | import asyncio
import logging
import threading
from datetime import datetime, timezone
from time import sleep
from typing import Any, Awaitable, Callable, Union
from redis.auth.err import RequestTokenErr, TokenRenewalErr
from redis.auth.idp import IdentityProviderInterface
from redis.auth.token import TokenResponse
l... | --- +++ @@ -13,6 +13,10 @@
class CredentialsListener:
+ """
+ Listeners that will be notified on events related to credentials.
+ Accepts callbacks and awaitable callbacks.
+ """
def __init__(self):
self._on_next = None
@@ -41,9 +45,19 @@ self.delay_in_ms = delay_in_ms
def... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/auth/token_manager.py |
Write docstrings for backend logic | from typing import Literal
from redis.client import Pipeline as RedisPipeline
from ...asyncio.client import Pipeline as AsyncioPipeline
from .commands import (
AGGREGATE_CMD,
CONFIG_CMD,
HYBRID_CMD,
INFO_CMD,
PROFILE_CMD,
SEARCH_CMD,
SPELLCHECK_CMD,
SYNDUMP_CMD,
AsyncSearchCommands... | --- +++ @@ -18,8 +18,16 @@
class Search(SearchCommands):
+ """
+ Create a client for talking to search.
+ It abstracts the API of the module and lets you just use the engine.
+ """
class BatchIndexer:
+ """
+ A batch indexer allows you to automatically batch
+ document indexi... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/__init__.py |
Write clean docstrings for readability | import threading
from typing import Any, Generic, List, TypeVar
from redis.typing import Number
T = TypeVar("T")
class WeightedList(Generic[T]):
def __init__(self):
self._items: List[tuple[Any, Number]] = []
self._lock = threading.RLock()
def add(self, item: Any, weight: float) -> None:
... | --- +++ @@ -7,12 +7,16 @@
class WeightedList(Generic[T]):
+ """
+ Thread-safe weighted list.
+ """
def __init__(self):
self._items: List[tuple[Any, Number]] = []
self._lock = threading.RLock()
def add(self, item: Any, weight: float) -> None:
+ """Add item with weight,... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/data_structure.py |
Write docstrings including parameters and return values | from __future__ import annotations
import json
from enum import Enum
from typing import Any, Awaitable, overload
from redis.client import NEVER_DECODE
from redis.commands.helpers import get_protocol_version
from redis.exceptions import DataError
from redis.typing import (
AsyncClientProtocol,
CommandsProtocol... | --- +++ @@ -49,6 +49,7 @@
class QuantizationOptions(Enum):
+ """Quantization options for the VADD command."""
NOQUANT = "NOQUANT"
BIN = "BIN"
@@ -56,6 +57,7 @@
class CallbacksOptions(Enum):
+ """Options that can be set for the commands callbacks"""
RAW = "RAW"
WITHSCORES = "WITHSCO... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/vectorset/commands.py |
Generate docstrings for script automation | import random
from abc import ABC, abstractmethod
# Maximum backoff between each retry in seconds
DEFAULT_CAP = 0.512
# Minimum backoff between each retry in seconds
DEFAULT_BASE = 0.008
class AbstractBackoff(ABC):
def reset(self):
pass
@abstractmethod
def compute(self, failures: int) -> float:... | --- +++ @@ -8,18 +8,27 @@
class AbstractBackoff(ABC):
+ """Backoff interface"""
def reset(self):
+ """
+ Reset internal state before an operation.
+ `reset` is called once at the beginning of
+ every call to `Retry.call_with_retry`
+ """
pass
@abstractmet... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/backoff.py |
Write docstrings for backend logic | import redis
from redis._parsers.helpers import bool_ok
from ..helpers import get_protocol_version, parse_to_list
from .commands import (
ALTER_CMD,
CREATE_CMD,
CREATERULE_CMD,
DEL_CMD,
DELETERULE_CMD,
GET_CMD,
INFO_CMD,
MGET_CMD,
MRANGE_CMD,
MREVRANGE_CMD,
QUERYINDEX_CMD,
... | --- +++ @@ -23,8 +23,15 @@
class TimeSeries(TimeSeriesCommands):
+ """
+ This class subclasses redis-py's `Redis` and implements RedisTimeSeries's
+ commands (prefixed with "ts").
+ The client allows to interact with RedisTimeSeries and use all of it's
+ functionality.
+ """
def __init__(se... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/timeseries/__init__.py |
Add standardized docstrings across the file | from typing import Optional
from ._util import to_string
from .document import Document
class Result:
def __init__(
self,
res,
hascontent,
duration=0,
has_payload=False,
with_scores=False,
field_encodings: Optional[dict] = None,
):
self.total ... | --- +++ @@ -5,6 +5,10 @@
class Result:
+ """
+ Represents the result of a search query, and has an array of Document
+ objects
+ """
def __init__(
self,
@@ -15,6 +19,12 @@ with_scores=False,
field_encodings: Optional[dict] = None,
):
+ """
+ - duration... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/result.py |
Add docstrings to improve collaboration | from enum import Enum
"Core exceptions raised by the Redis client"
class ExceptionType(Enum):
NETWORK = "network"
TLS = "tls"
AUTH = "auth"
SERVER = "server"
class RedisError(Exception):
def __init__(self, *args, status_code: str = None):
super().__init__(*args)
self.error_type ... | --- +++ @@ -75,6 +75,13 @@
class OutOfMemoryError(ResponseError):
+ """
+ Indicates the database is full. Can only occur when either:
+ * Redis maxmemory-policy=noeviction
+ * Redis maxmemory-policy=volatile* and there are no evictable keys
+
+ For more information see `Memory optimization in Red... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/exceptions.py |
Write docstrings for utility functions | import time
from abc import ABC, abstractmethod
from redis.asyncio.multidb.database import AsyncDatabase, Databases
from redis.data_structure import WeightedList
from redis.multidb.circuit import State as CBState
from redis.multidb.exception import (
NoValidDatabaseException,
TemporaryUnavailableException,
)
... | --- +++ @@ -16,10 +16,12 @@ class AsyncFailoverStrategy(ABC):
@abstractmethod
async def database(self) -> AsyncDatabase:
+ """Select the database according to the strategy."""
pass
@abstractmethod
def set_databases(self, databases: Databases) -> None:
+ """Set the database s... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/multidb/failover.py |
Create structured documentation for my script | from typing import Optional
from ._util import to_string
class Suggestion:
def __init__(
self, string: str, score: float = 1.0, payload: Optional[str] = None
) -> None:
self.string = to_string(string)
self.payload = to_string(payload)
self.score = score
def __repr__(self... | --- +++ @@ -4,6 +4,10 @@
class Suggestion:
+ """
+ Represents a single suggestion being sent or returned from the
+ autocomplete server
+ """
def __init__(
self, string: str, score: float = 1.0, payload: Optional[str] = None
@@ -17,6 +21,11 @@
class SuggestionParser:
+ """
+ In... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/suggestion.py |
Write docstrings including parameters and return values | from abc import ABC, abstractmethod
from redis.auth.token import TokenInterface
"""
This interface is the facade of an identity provider
"""
class IdentityProviderInterface(ABC):
@abstractmethod
def request_token(self, force_refresh=False) -> TokenInterface:
pass
class IdentityProviderConfigInter... | --- +++ @@ -8,6 +8,10 @@
class IdentityProviderInterface(ABC):
+ """
+ Receive a token from the identity provider.
+ Receiving a token only works when being authenticated.
+ """
@abstractmethod
def request_token(self, force_refresh=False) -> TokenInterface:
@@ -15,7 +19,10 @@
class Ident... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/auth/idp.py |
Add docstrings following best practices | from redis._parsers.helpers import bool_ok
from ..helpers import get_protocol_version, parse_to_list
from .commands import * # noqa
from .info import BFInfo, CFInfo, CMSInfo, TDigestInfo, TopKInfo
class AbstractBloom:
@staticmethod
def append_items(params, items):
params.extend(["ITEMS"])
p... | --- +++ @@ -6,68 +6,90 @@
class AbstractBloom:
+ """
+ The client allows to interact with RedisBloom and use all of
+ it's functionality.
+
+ - BF for Bloom Filter
+ - CF for Cuckoo Filter
+ - CMS for Count-Min Sketch
+ - TOPK for TopK Data Structure
+ - TDIGEST for estimate rank statistics
... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/bf/__init__.py |
Generate descriptive docstrings automatically | #!/usr/bin/env python3
import argparse
import asyncio
import json
import os
import statistics
import subprocess
import sys
import time
from dataclasses import dataclass, field, asdict
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Dict, List, Optional, Any
try:
import psutil
... | --- +++ @@ -1,4 +1,31 @@ #!/usr/bin/env python3
+"""
+OpenTelemetry Benchmark for redis-py.
+
+This module provides benchmarking infrastructure to measure the performance impact
+of OpenTelemetry instrumentation on redis-py operations.
+
+The benchmark uses a comprehensive load generator that exercises all Redis operat... | https://raw.githubusercontent.com/redis/redis-py/HEAD/benchmarks/otel_benchmark.py |
Generate helpful docstrings for debugging | from enum import Enum
from typing import Any, Dict, List, Optional, Union
from redis.utils import experimental
try:
from typing import Self # Py 3.11+
except ImportError:
from typing_extensions import Self
from redis.commands.search.aggregation import Limit, Reducer
from redis.commands.search.query import F... | --- +++ @@ -20,18 +20,42 @@ scorer: Optional[str] = None,
yield_score_as: Optional[str] = None,
) -> None:
+ """
+ Create a new hybrid search query object.
+
+ Args:
+ query_string: The query string.
+ scorer: Scoring algorithm for text search query.
+ ... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/hybrid_query.py |
Generate documentation strings for clarity | import datetime
from redis.utils import str_if_bytes
def timestamp_to_datetime(response):
if not response:
return None
try:
response = int(response)
except ValueError:
return None
return datetime.datetime.fromtimestamp(response)
def parse_debug_object(response):
# The 't... | --- +++ @@ -4,6 +4,7 @@
def timestamp_to_datetime(response):
+ "Converts a unix timestamp to a Python datetime object"
if not response:
return None
try:
@@ -14,6 +15,7 @@
def parse_debug_object(response):
+ "Parse the results of Redis's DEBUG OBJECT command into a Python dict"
# Th... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/_parsers/helpers.py |
Add docstrings to improve code quality | from enum import Enum
class IndexType(Enum):
HASH = 1
JSON = 2
class IndexDefinition:
def __init__(
self,
prefix=[],
filter=None,
language_field=None,
language=None,
score_field=None,
score=1.0,
payload_field=None,
index_type=None... | --- +++ @@ -2,12 +2,15 @@
class IndexType(Enum):
+ """Enum of the currently supported index types."""
HASH = 1
JSON = 2
class IndexDefinition:
+ """IndexDefinition is used to define a index definition for automatic
+ indexing on Hash or Json update."""
def __init__(
self,
@... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/index_definition.py |
Add detailed documentation for each class | from typing import Iterable
class RequestTokenErr(Exception):
def __init__(self, *args):
super().__init__(*args)
class InvalidTokenSchemaErr(Exception):
def __init__(self, missing_fields: Iterable[str] = []):
super().__init__(
"Unexpected token schema. Following fields are miss... | --- +++ @@ -2,12 +2,18 @@
class RequestTokenErr(Exception):
+ """
+ Represents an exception during token request.
+ """
def __init__(self, *args):
super().__init__(*args)
class InvalidTokenSchemaErr(Exception):
+ """
+ Represents an exception related to invalid token schema.
+ ... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/auth/err.py |
Add docstrings with type hints explained | import asyncio
import threading
from typing import Any, Callable, Coroutine
class BackgroundScheduler:
def __init__(self):
self._next_timer = None
self._event_loops = []
self._lock = threading.Lock()
self._stopped = False
def __del__(self):
self.stop()
def stop(s... | --- +++ @@ -4,6 +4,9 @@
class BackgroundScheduler:
+ """
+ Schedules background tasks execution either in separate thread or in the running event loop.
+ """
def __init__(self):
self._next_timer = None
@@ -15,6 +18,9 @@ self.stop()
def stop(self):
+ """
+ Stop a... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/background.py |
Add docstrings including usage examples | import enum
import ipaddress
import logging
import re
import threading
import time
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Dict, List, Literal, Optional, Union
from redis.observability.attributes import get_pool_name
from redis.observability.recorder import (
record_connection_handoff... | --- +++ @@ -28,6 +28,7 @@
class EndpointType(enum.Enum):
+ """Valid endpoint types used in CLIENT MAINT_NOTIFICATIONS command."""
INTERNAL_IP = "internal-ip"
INTERNAL_FQDN = "internal-fqdn"
@@ -36,6 +37,7 @@ NONE = "none"
def __str__(self):
+ """Return the string value of the enum."... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/maint_notifications.py |
Help me comply with documentation standards | import logging
from abc import ABC, abstractmethod
from typing import Any, Callable, Optional, Tuple, Union
logger = logging.getLogger(__name__)
class CredentialProvider:
def get_credentials(self) -> Union[Tuple[str], Tuple[str, str]]:
raise NotImplementedError("get_credentials must be implemented")
... | --- +++ @@ -6,6 +6,9 @@
class CredentialProvider:
+ """
+ Credentials Provider.
+ """
def get_credentials(self) -> Union[Tuple[str], Tuple[str, str]]:
raise NotImplementedError("get_credentials must be implemented")
@@ -19,9 +22,19 @@
class StreamingCredentialProvider(CredentialProvider... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/credentials.py |
Please document this code using docstrings |
from datetime import datetime
from typing import TYPE_CHECKING, List, Optional
from redis.observability.attributes import (
ConnectionState,
GeoFailoverReason,
PubSubDirection,
)
from redis.observability.metrics import CloseReason, RedisMetricsCollector
from redis.observability.providers import get_observ... | --- +++ @@ -1,3 +1,24 @@+"""
+Async-compatible API for recording observability metrics.
+
+This module provides an async-safe interface for Redis async client code to record
+metrics without needing to know about OpenTelemetry internals. It reuses the same
+RedisMetricsCollector and configuration as the sync recorder.
... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/observability/recorder.py |
Add docstrings to meet PEP guidelines | import logging
import threading
import time as mod_time
import uuid
from types import SimpleNamespace, TracebackType
from typing import Optional, Type
from redis.exceptions import LockError, LockNotOwnedError
from redis.typing import Number
logger = logging.getLogger(__name__)
class Lock:
lua_release = None
... | --- +++ @@ -12,6 +12,13 @@
class Lock:
+ """
+ A shared, distributed Lock. Using Redis for locking allows the Lock
+ to be shared across processes and/or machines.
+
+ It's left to the user to resolve deadlock issues and make sure
+ multiple clients play nicely together.
+ """
lua_release =... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/lock.py |
Generate docstrings for script automation | import asyncio
import socket
import sys
from logging import getLogger
from typing import Callable, List, Optional, TypedDict, Union
if sys.version_info.major >= 3 and sys.version_info.minor >= 11:
from asyncio import timeout as async_timeout
else:
from async_timeout import timeout as async_timeout
from ..exce... | --- +++ @@ -39,6 +39,7 @@
class _HiredisParser(BaseParser, PushNotificationsParser):
+ "Parser class for connections using Hiredis"
def __init__(self, socket_read_size):
if not HIREDIS_AVAILABLE:
@@ -197,6 +198,7 @@
class _AsyncHiredisParser(AsyncBaseParser, AsyncPushNotificationsParser):
+ ... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/_parsers/hiredis.py |
Document functions with clear intent | import asyncio
import logging
import threading
import uuid
from types import SimpleNamespace
from typing import TYPE_CHECKING, Awaitable, Optional, Union
from redis.exceptions import LockError, LockNotOwnedError
from redis.typing import Number
if TYPE_CHECKING:
from redis.asyncio import Redis, RedisCluster
logge... | --- +++ @@ -15,6 +15,13 @@
class Lock:
+ """
+ A shared, distributed Lock. Using Redis for locking allows the Lock
+ to be shared across processes and/or machines.
+
+ It's left to the user to resolve deadlock issues and make sure
+ multiple clients play nicely together.
+ """
lua_release =... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/lock.py |
Add concise docstrings to each method | from abc import abstractmethod
from typing import Optional, Union
from redis.asyncio import Redis, RedisCluster
from redis.data_structure import WeightedList
from redis.multidb.circuit import CircuitBreaker
from redis.multidb.database import AbstractDatabase, BaseDatabase
from redis.typing import Number
class AsyncD... | --- +++ @@ -9,25 +9,30 @@
class AsyncDatabase(AbstractDatabase):
+ """Database with an underlying asynchronous redis client."""
@property
@abstractmethod
def client(self) -> Union[Redis, RedisCluster]:
+ """The underlying redis client."""
pass
@client.setter
@abstract... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/multidb/database.py |
Insert docstrings into my code | import asyncio
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Mapping, Optional, Union
from redis.http.http_client import HttpClient, HttpResponse
DEFAULT_USER_AGENT = "HttpClient/1.0 (+https://example.invalid)"
DEFAULT_TIMEOUT = 30.0
RETRY_STATUS_CODES =... | --- +++ @@ -22,6 +22,8 @@ timeout: Optional[float] = None,
expect_json: bool = True,
) -> Union[HttpResponse, Any]:
+ """
+ Invoke HTTP GET request."""
pass
@abstractmethod
@@ -35,6 +37,8 @@ timeout: Optional[float] = None,
expect_json: bool = True,
... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/http/http_client.py |
Add docstrings for production code | from abc import ABC, abstractmethod
from redis.multidb.failure_detector import FailureDetector
class AsyncFailureDetector(ABC):
@abstractmethod
async def register_failure(self, exception: Exception, cmd: tuple) -> None:
pass
@abstractmethod
async def register_command_execution(self, cmd: tup... | --- +++ @@ -6,18 +6,24 @@ class AsyncFailureDetector(ABC):
@abstractmethod
async def register_failure(self, exception: Exception, cmd: tuple) -> None:
+ """Register a failure that occurred during command execution."""
pass
@abstractmethod
async def register_command_execution(self, ... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/multidb/failure_detector.py |
Document helper functions with docstrings | from __future__ import annotations
from json import JSONDecoder, JSONEncoder
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .bf import BFBloom, CFBloom, CMSBloom, TDigestBloom, TOPKBloom
from .json import JSON
from .search import AsyncSearch, Search
from .timeseries import TimeSeries
from... | --- +++ @@ -12,8 +12,12 @@
class RedisModuleCommands:
+ """This class contains the wrapper functions to bring supported redis
+ modules into the command namespace.
+ """
def json(self, encoder=JSONEncoder(), decoder=JSONDecoder()) -> JSON:
+ """Access the json namespace, providing support for... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/redismodules.py |
Generate descriptive docstrings automatically | import os
from json import JSONDecodeError, loads
from typing import Dict, List, Optional, Tuple, Union
from redis.exceptions import DataError
from redis.utils import deprecated_function
from ._util import JsonType
from .decoders import decode_dict_keys
from .path import Path
class JSONCommands:
def arrappend(... | --- +++ @@ -11,10 +11,16 @@
class JSONCommands:
+ """json commands."""
def arrappend(
self, name: str, path: Optional[str] = Path.root_path(), *args: JsonType
) -> List[Optional[int]]:
+ """Append the objects ``args`` to the array under the
+ ``path` in key ``name``.
+
+ ... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/json/commands.py |
Create simple docstrings for beginners | import asyncio
import logging
from typing import Any, Awaitable, Callable, List, Literal, Optional, Union
from redis.asyncio.client import PubSubHandler
from redis.asyncio.multidb.command_executor import DefaultCommandExecutor
from redis.asyncio.multidb.config import (
DEFAULT_GRACE_PERIOD,
DatabaseConfig,
... | --- +++ @@ -33,6 +33,10 @@
@experimental
class MultiDBClient(AsyncRedisModuleCommands, AsyncCoreCommands):
+ """
+ Client that operates on multiple logical Redis databases.
+ Should be used in Client-side geographic failover database setups.
+ """
def __init__(self, config: MultiDbConfig):
... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/multidb/client.py |
Add docstrings explaining edge cases | import asyncio
import copy
import inspect
import re
import time
import warnings
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
MutableMapping,
Optional,
Protocol,
Set,
Tuple,
Type,
T... | --- +++ @@ -118,6 +118,17 @@ class Redis(
AbstractRedis, AsyncRedisModuleCommands, AsyncCoreCommands, AsyncSentinelCommands
):
+ """
+ Implementation of the Redis protocol.
+
+ This abstract class provides a Python interface to all Redis commands
+ and an implementation of the Redis protocol.
+
+ P... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/client.py |
Write clean docstrings for readability | import errno
import io
import socket
from io import SEEK_END
from typing import Optional, Union
from ..exceptions import ConnectionError, TimeoutError
from ..utils import SSL_AVAILABLE
NONBLOCKING_EXCEPTION_ERROR_NUMBERS = {BlockingIOError: errno.EWOULDBLOCK}
if SSL_AVAILABLE:
import ssl
if hasattr(ssl, "SS... | --- +++ @@ -36,6 +36,9 @@ self._buffer = io.BytesIO()
def unread_bytes(self) -> int:
+ """
+ Remaining unread length of buffer
+ """
pos = self._buffer.tell()
end = self._buffer.seek(0, SEEK_END)
self._buffer.seek(pos)
@@ -115,12 +118,21 @@ return d... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/_parsers/socket.py |
Create documentation strings for testing functions | from ..exceptions import DataError
class Encoder:
__slots__ = "encoding", "encoding_errors", "decode_responses"
def __init__(self, encoding, encoding_errors, decode_responses):
self.encoding = encoding
self.encoding_errors = encoding_errors
self.decode_responses = decode_responses
... | --- +++ @@ -2,6 +2,7 @@
class Encoder:
+ "Encode strings to bytes-like and decode bytes-like to strings"
__slots__ = "encoding", "encoding_errors", "decode_responses"
@@ -11,6 +12,7 @@ self.decode_responses = decode_responses
def encode(self, value):
+ "Return a bytestring or bytes... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/_parsers/encoders.py |
Generate descriptive docstrings automatically | from ..helpers import nativestr
def list_to_dict(aList):
return {nativestr(aList[i][0]): nativestr(aList[i][1]) for i in range(len(aList))}
def parse_range(response, **kwargs):
return [tuple((r[0], float(r[1]))) for r in response]
def parse_m_range(response):
res = []
for item in response:
... | --- +++ @@ -6,10 +6,12 @@
def parse_range(response, **kwargs):
+ """Parse range response. Used by TS.RANGE and TS.REVRANGE."""
return [tuple((r[0], float(r[1]))) for r in response]
def parse_m_range(response):
+ """Parse multi range response. Used by TS.MRANGE and TS.MREVRANGE."""
res = []
... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/timeseries/utils.py |
Write docstrings including parameters and return values | from typing import Union
from .aggregation import Asc, Desc, Reducer, SortDirection
class FieldOnlyReducer(Reducer):
def __init__(self, field: str) -> None:
super().__init__(field)
self._field = field
class count(Reducer):
NAME = "COUNT"
def __init__(self) -> None:
super().__... | --- +++ @@ -4,6 +4,7 @@
class FieldOnlyReducer(Reducer):
+ """See https://redis.io/docs/interact/search-and-query/search/aggregations/"""
def __init__(self, field: str) -> None:
super().__init__(field)
@@ -11,6 +12,9 @@
class count(Reducer):
+ """
+ Counts the number of results in the g... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/reducers.py |
Provide docstrings following PEP 257 | from redis.client import NEVER_DECODE
from redis.utils import deprecated_function
BF_RESERVE = "BF.RESERVE"
BF_ADD = "BF.ADD"
BF_MADD = "BF.MADD"
BF_INSERT = "BF.INSERT"
BF_EXISTS = "BF.EXISTS"
BF_MEXISTS = "BF.MEXISTS"
BF_SCANDUMP = "BF.SCANDUMP"
BF_LOADCHUNK = "BF.LOADCHUNK"
BF_INFO = "BF.INFO"
BF_CARD = "BF.CARD"
... | --- +++ @@ -57,8 +57,15 @@
class BFCommands:
+ """Bloom Filter commands."""
def create(self, key, errorRate, capacity, expansion=None, noScale=None):
+ """
+ Create a new Bloom Filter `key` with desired probability of false positives
+ `errorRate` expected entries to be inserted as `c... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/bf/commands.py |
Generate consistent documentation across files | import asyncio
import logging
from abc import ABC, abstractmethod
from enum import Enum
from typing import List, Optional, Tuple, Union
from redis.asyncio import Redis
from redis.asyncio.http.http_client import DEFAULT_TIMEOUT, AsyncHTTPClientWrapper
from redis.backoff import NoBackoff
from redis.http.http_client impo... | --- +++ @@ -22,23 +22,30 @@ class HealthCheck(ABC):
@abstractmethod
async def check_health(self, database) -> bool:
+ """Function to determine the health status."""
pass
class HealthCheckPolicy(ABC):
+ """
+ Health checks execution policy.
+ """
@property
@abstractmet... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/multidb/healthcheck.py |
Add return value explanations in docstrings | import copy
import re
from ..helpers import nativestr
def bulk_of_jsons(d):
def _f(b):
for index, item in enumerate(b):
if item is not None:
b[index] = d(item)
return b
return _f
def decode_dict_keys(obj):
newobj = copy.copy(obj)
for k in obj.keys():
... | --- +++ @@ -5,6 +5,9 @@
def bulk_of_jsons(d):
+ """Replace serialized JSON values with objects in a
+ bulk array response (list).
+ """
def _f(b):
for index, item in enumerate(b):
@@ -16,6 +19,7 @@
def decode_dict_keys(obj):
+ """Decode the keys of the given dictionary with utf-8."""... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/json/decoders.py |
Add standardized docstrings across the file | import copy
import logging
import re
import threading
import time
from itertools import chain
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Literal,
Mapping,
Optional,
Set,
Type,
Union,
)
from redis._parsers.encoders import Encoder
from redis._parsers.helper... | --- +++ @@ -107,6 +107,7 @@
class CaseInsensitiveDict(dict):
+ "Case insensitive dict implementation. Assumes string keys only."
def __init__(self, data: Dict[str, str]) -> None:
for k, v in data.items():
@@ -137,12 +138,65 @@
class Redis(RedisModuleCommands, CoreCommands, SentinelCommands):
... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/client.py |
Provide docstrings following PEP 257 | import copy
import random
import string
from typing import Any, Iterable, List, Tuple
import redis
from redis.typing import KeysT, KeyT
def list_or_args(keys: KeysT, args: Tuple[KeyT, ...]) -> List[KeyT]:
# returns a single new list combining keys and args
try:
iter(keys)
# a string or bytes ... | --- +++ @@ -25,6 +25,7 @@
def nativestr(x):
+ """Return the decoded binary string, or a string, depending on type."""
r = x.decode("utf-8", "replace") if isinstance(x, bytes) else x
if r == "null":
return
@@ -32,12 +33,14 @@
def delist(x):
+ """Given a list of binaries, return the strin... | https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/helpers.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.