instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Can you add docstrings to this Python file? |
import sys
def get_integer_input(prompt: str, attempts: int) -> int | None:
for i in range(attempts, 0, -1):
try:
# Attempt to parse user input as integer
n = int(input(prompt))
return n
except ValueError:
# Invalid input: notify and decrement chanc... | --- +++ @@ -1,8 +1,39 @@+"""
+A simple program to calculate the sum of digits of a user-input integer.
+
+Features:
+- Input validation with limited attempts.
+- Graceful exit if attempts are exhausted.
+- Sum of digits computed iteratively.
+
+Doctests:
+ >>> sum_of_digits(123)
+ 6
+ >>> sum_of_digits(0)
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/sum_of_digits_of_a_number.py |
Document all public functions with docstrings | class Swapper:
def __init__(self, x, y):
if not isinstance(x, (int, float)) or not isinstance(y, (float, int)):
raise ValueError("Both x and y should be integers.")
self.x = x
self.y = y
def display_values(self, message):
print(f"{message} x: {self.x}, y: {self.y}"... | --- +++ @@ -1,6 +1,32 @@ class Swapper:
+ """
+ A class to perform swapping of two values.
+
+ Methods:
+ -------
+ swap_tuple_unpacking(self):
+ Swaps the values of x and y using a tuple unpacking method.
+
+ swap_temp_variable(self):
+ Swaps the values of x and y using a temporary vari... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/swap.py |
Document this code for team use | # -----------------------------------------------------------------------------
# You are givent two timestams in the format: Day dd Mon yyyy hh:mm:ss +xxxx
# where +xxxx represents the timezone.
# Input Format:
# The first line contains T, the number of test cases.
# Each test case contains two lines, representing th... | --- +++ @@ -1,3 +1,9 @@+"""
+Time Delta Calculator
+
+This module provides functionality to calculate the absolute difference
+in seconds between two timestamps in the format: Day dd Mon yyyy hh:mm:ss +xxxx
+"""
# -----------------------------------------------------------------------------
# You are givent two times... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/time_delta.py |
Write docstrings describing functionality |
import math
import pickle
from colorama import Fore, Style
switcher = {
"r": Fore.RED,
"bk": Fore.BLACK,
"b": Fore.BLUE,
"g": Fore.GREEN,
"y": Fore.YELLOW,
"m": Fore.MAGENTA,
"c": Fore.CYAN,
"w": Fore.WHITE,
}
def paint(str, color="r"):
if color in switcher:
str = switch... | --- +++ @@ -1,3 +1,36 @@+"""@Author: Anurag Kumar(mailto:anuragkumarak95@gmail.com)
+This module is used for generating a TF-IDF file or values from a list of files that contains docs.
+
+What is TF-IDF : https://en.wikipedia.org/wiki/Tf%E2%80%93idf
+
+python:
+ - 3.5
+
+pre-requisites:
+ - colorama==0.3.9
+
+sample ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/tf_idf_generator.py |
Add docstrings for utility scripts |
def is_leap_year(year: int) -> bool:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
if __name__ == "__main__":
import doctest
doctest.testmod()
year_input = input("Enter a year: ").strip()
try:
year = int(year_input)
if is_leap_year(year):
print(f"{ye... | --- +++ @@ -1,6 +1,30 @@+"""
+Leap Year Checker.
+
+Determine whether a given year is a leap year.
+
+Doctests:
+
+>>> is_leap_year(2000)
+True
+>>> is_leap_year(1900)
+False
+>>> is_leap_year(2024)
+True
+>>> is_leap_year(2023)
+False
+"""
def is_leap_year(year: int) -> bool:
+ """
+ Return True if year is ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/to check leap year.py |
Document all public functions with docstrings |
import hashlib
import json
import logging
import os
from pathlib import Path
from typing import Any, Dict, List, Optional
from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.exceptions import InvalidWheelFilena... | --- +++ @@ -1,3 +1,5 @@+"""Cache Management
+"""
import hashlib
import json
@@ -22,11 +24,16 @@
def _hash_dict(d: Dict[str, str]) -> str:
+ """Return a stable sha224 of a dictionary."""
s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
return hashlib.sha224(s.encode("ascii... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/cache.py |
Add docstrings for internal functions |
import logging
import os
import pathlib
import site
import sys
import textwrap
from collections import OrderedDict
from types import TracebackType
from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Type, Union
from pip._vendor.certifi import where
from pip._vendor.packaging.version import Version... | --- +++ @@ -1,3 +1,5 @@+"""Build Environment used for isolation during sdist building
+"""
import logging
import os
@@ -41,6 +43,11 @@
def get_runnable_pip() -> str:
+ """Get a file to pass to a Python executable, to run the currently-running pip.
+
+ This is used to run a pip subprocess, for installing r... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/build_env.py |
Expand my code with proper documentation strings |
import optparse
import os
import sys
from itertools import chain
from typing import Any, Iterable, List, Optional
from pip._internal.cli.main_parser import create_main_parser
from pip._internal.commands import commands_dict, create_command
from pip._internal.metadata import get_default_environment
def autocomplete(... | --- +++ @@ -1,3 +1,5 @@+"""Logic that powers autocompletion installed by ``pip completion``.
+"""
import optparse
import os
@@ -11,6 +13,7 @@
def autocomplete() -> None:
+ """Entry Point for completion of main and subcommand options."""
# Don't complete if user hasn't sourced bash_completion file.
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/cli/autocompletion.py |
Write proper docstrings for these functions |
# The following comment should be removed at some point in the future.
# mypy: strict-optional=False
import importlib.util
import logging
import os
import textwrap
from functools import partial
from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values
from textwrap import dedent
from typing import... | --- +++ @@ -1,3 +1,11 @@+"""
+shared options and groups
+
+The principle here is to define options once, but *not* instantiate them
+globally. One reason being that options with action='append' can carry state
+between parses. pip parses general options twice internally, and shouldn't
+pass on state. To be consistent, ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/cli/cmdoptions.py |
Annotate my code with docstrings |
import logging
import os
import sys
from optparse import Values
from typing import TYPE_CHECKING, List, Optional
from pip._vendor import certifi
from pip._internal.cli.base_command import Command
from pip._internal.cli.command_context import CommandContextMixIn
if TYPE_CHECKING:
from ssl import SSLContext
... | --- +++ @@ -1,3 +1,10 @@+"""
+Contains command classes which may interact with an index / the network.
+
+Unlike its sister module, req_command, this module still uses lazy imports
+so commands which don't always hit the network (e.g. list w/o --outdated or
+--uptodate) don't need waste time importing PipSession and fr... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/cli/index_command.py |
Add docstrings to clarify complex logic |
import logging
from functools import partial
from optparse import Values
from typing import Any, List, Optional, Tuple
from pip._internal.cache import WheelCache
from pip._internal.cli import cmdoptions
from pip._internal.cli.index_command import IndexGroupCommand
from pip._internal.cli.index_command import SessionCo... | --- +++ @@ -1,3 +1,9 @@+"""Contains the RequirementCommand base class.
+
+This class is in a separate module so the commands that do not always
+need PackageFinder capability don't unnecessarily import the
+PackageFinder machinery and all its vendored dependencies, etc.
+"""
import logging
from functools import par... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/cli/req_command.py |
Generate missing documentation strings |
import importlib
from collections import namedtuple
from typing import Any, Dict, Optional
from pip._internal.cli.base_command import Command
CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary")
# This dictionary does a bunch of heavy lifting for help output:
# - Enables avoiding additional (... | --- +++ @@ -1,3 +1,6 @@+"""
+Package containing all pip commands
+"""
import importlib
from collections import namedtuple
@@ -104,6 +107,9 @@
def create_command(name: str, **kwargs: Any) -> Command:
+ """
+ Create an instance of the Command class with the given name.
+ """
module_path, class_name,... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/commands/__init__.py |
Add clean documentation to messy code |
import logging
import logging.config
import optparse
import os
import sys
import traceback
from optparse import Values
from typing import List, Optional, Tuple
from pip._vendor.rich import reconfigure
from pip._vendor.rich import traceback as rich_traceback
from pip._internal.cli import cmdoptions
from pip._internal... | --- +++ @@ -1,3 +1,4 @@+"""Base Command class, and related routines"""
import logging
import logging.config
@@ -78,6 +79,10 @@ pass
def handle_pip_version_check(self, options: Values) -> None:
+ """
+ This is a no-op so that commands by default do not do the pip version
+ check.
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/cli/base_command.py |
Create docstrings for API functions | import sys
import textwrap
from optparse import Values
from typing import List
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import SUCCESS
from pip._internal.utils.misc import get_prog
BASE_COMPLETION = """
# pip {shell} completion start{script}# pip {shell} completion end
""... | --- +++ @@ -73,6 +73,7 @@
class CompletionCommand(Command):
+ """A helper command to be used for command completion."""
ignore_require_venv = True
@@ -113,6 +114,7 @@ self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int:
+ """Prin... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/commands/completion.py |
Add docstrings for production code |
import logging
import optparse
import shutil
import sys
import textwrap
from contextlib import suppress
from typing import Any, Dict, Generator, List, Optional, Tuple
from pip._internal.cli.status_codes import UNKNOWN_ERROR
from pip._internal.configuration import Configuration, ConfigurationError
from pip._internal.u... | --- +++ @@ -1,3 +1,4 @@+"""Base option parser setup"""
import logging
import optparse
@@ -15,6 +16,7 @@
class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
+ """A prettier/less verbose help formatter for optparse."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
# help positio... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/cli/parser.py |
Fully document this Python code with docstrings |
import os
import subprocess
import sys
from typing import List, Optional, Tuple
from pip._internal.build_env import get_runnable_pip
from pip._internal.cli import cmdoptions
from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
from pip._internal.commands import commands_dict, get_sim... | --- +++ @@ -1,3 +1,5 @@+"""A single place for constructing and exposing the main parser
+"""
import os
import subprocess
@@ -15,6 +17,7 @@
def create_main_parser() -> ConfigOptionParser:
+ """Creates and returns the main parser for pip's CLI"""
parser = ConfigOptionParser(
usage="\n%prog <com... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/cli/main_parser.py |
Help me document legacy Python code | import logging
import os
import subprocess
from optparse import Values
from typing import Any, List, Optional
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.configuration import (
Configuration,
Kind,
get_configuration_files,
... | --- +++ @@ -20,6 +20,29 @@
class ConfigurationCommand(Command):
+ """
+ Manage local and global configuration.
+
+ Subcommands:
+
+ - list: List the active configuration (or from the file specified)
+ - edit: Edit the configuration file in an editor
+ - get: Get the value associated with command.o... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/commands/configuration.py |
Write beginner-friendly docstrings | import errno
import json
import operator
import os
import shutil
import site
from optparse import SUPPRESS_HELP, Values
from typing import List, Optional
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.rich import print_json
from pip._internal.cache import WheelCache
from pip._internal.cli ... | --- +++ @@ -51,6 +51,17 @@
class InstallCommand(RequirementCommand):
+ """
+ Install packages from:
+
+ - PyPI (and other indexes) using requirement specifiers.
+ - VCS project urls.
+ - Local project directories.
+ - Local or remote source archives.
+
+ pip also supports installing from "requi... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/commands/install.py |
Add docstrings for production code | import hashlib
import logging
import sys
from optparse import Values
from typing import List
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES
from pip._internal.utils.misc import read_chunks,... | --- +++ @@ -13,6 +13,12 @@
class HashCommand(Command):
+ """
+ Compute a hash of a local package archive.
+
+ These can be used with --hash in a requirements file to do repeatable
+ installs.
+ """
usage = "%prog [options] <file> ..."
ignore_require_venv = True
@@ -45,8 +51,9 @@
def _... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/commands/hash.py |
Help me write clear docstrings | import logging
from optparse import Values
from typing import Any, Iterable, List, Optional
from pip._vendor.packaging.version import Version
from pip._internal.cli import cmdoptions
from pip._internal.cli.req_command import IndexGroupCommand
from pip._internal.cli.status_codes import ERROR, SUCCESS
from pip._interna... | --- +++ @@ -20,6 +20,9 @@
class IndexCommand(IndexGroupCommand):
+ """
+ Inspect information available from package indexes.
+ """
ignore_require_venv = True
usage = """
@@ -79,6 +82,9 @@ target_python: Optional[TargetPython] = None,
ignore_requires_python: Optional[bool] = Non... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/commands/index.py |
Create documentation strings for testing functions | import logging
import shutil
import sys
import textwrap
import xmlrpc.client
from collections import OrderedDict
from optparse import Values
from typing import TYPE_CHECKING, Dict, List, Optional, TypedDict
from pip._vendor.packaging.version import parse as parse_version
from pip._internal.cli.base_command import Com... | --- +++ @@ -31,6 +31,7 @@
class SearchCommand(Command, SessionCommandMixin):
+ """Search for PyPI packages whose name or summary contains <query>."""
usage = """
%prog [options] <query>"""
@@ -83,6 +84,11 @@
def transform_hits(hits: List[Dict[str, str]]) -> List["TransformedHit"]:
+ """
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/commands/search.py |
Document all endpoints with docstrings | import logging
from optparse import Values
from typing import Generator, Iterable, Iterator, List, NamedTuple, Optional
from pip._vendor.packaging.requirements import InvalidRequirement
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.cli.base_command import Command
from pip._internal.cli.... | --- +++ @@ -14,6 +14,11 @@
class ShowCommand(Command):
+ """
+ Show information about one or more installed packages.
+
+ The output is in RFC-compliant mail header format.
+ """
usage = """
%prog [options] <package> ..."""
@@ -66,6 +71,12 @@
def search_packages_info(query: List[str]) ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/commands/show.py |
Add docstrings for production code | import json
import logging
from optparse import Values
from typing import TYPE_CHECKING, Generator, List, Optional, Sequence, Tuple, cast
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.packaging.version import Version
from pip._internal.cli import cmdoptions
from pip._internal.cli.index_co... | --- +++ @@ -20,6 +20,11 @@ from pip._internal.network.session import PipSession
class _DistWithLatestInfo(BaseDistribution):
+ """Give the distribution object a couple of extra fields.
+
+ These will be populated during ``get_outdated()``. This is dirty but
+ makes the rest of the code m... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/commands/list.py |
Add verbose docstrings with examples | import abc
from typing import TYPE_CHECKING, Optional
from pip._internal.metadata.base import BaseDistribution
from pip._internal.req import InstallRequirement
if TYPE_CHECKING:
from pip._internal.index.package_finder import PackageFinder
class AbstractDistribution(metaclass=abc.ABCMeta):
def __init__(self... | --- +++ @@ -9,6 +9,23 @@
class AbstractDistribution(metaclass=abc.ABCMeta):
+ """A base class for handling installable artifacts.
+
+ The requirements for anything installable are as follows:
+
+ - we must be able to determine the requirement name
+ (or we can't correctly handle the non-upgrade case... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/distributions/base.py |
Help me write clear docstrings |
import configparser
import locale
import os
import sys
from typing import Any, Dict, Iterable, List, NewType, Optional, Tuple
from pip._internal.exceptions import (
ConfigurationError,
ConfigurationFileCouldNotBeLoaded,
)
from pip._internal.utils import appdirs
from pip._internal.utils.compat import WINDOWS
f... | --- +++ @@ -1,3 +1,15 @@+"""Configuration management setup
+
+Some terminology:
+- name
+ As written in config files.
+- value
+ Value associated with a name
+- key
+ Name combined with it's section (section.name)
+- variant
+ A single word describing where the configuration key-value pair came from
+"""
import ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/configuration.py |
Write docstrings for utility functions | from typing import TYPE_CHECKING, Optional
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.metadata import (
BaseDistribution,
FilesystemWheel,
get_wheel_distribution,
)
if TYPE_CHECKING:
from pip._internal... | --- +++ @@ -14,12 +14,20 @@
class WheelDistribution(AbstractDistribution):
+ """Represents a wheel distribution.
+
+ This does not need any preparation as wheels can be directly unpacked.
+ """
@property
def build_tracker_id(self) -> Optional[str]:
return None
def get_metadata_d... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/distributions/wheel.py |
Document helper functions with docstrings | import logging
import os
import sys
import sysconfig
import typing
from pip._internal.exceptions import InvalidSchemeCombination, UserInstallationInvalid
from pip._internal.models.scheme import SCHEME_KEYS, Scheme
from pip._internal.utils.virtualenv import running_under_virtualenv
from .base import change_root, get_m... | --- +++ @@ -27,6 +27,24 @@
def _should_use_osx_framework_prefix() -> bool:
+ """Check for Apple's ``osx_framework_library`` scheme.
+
+ Python distributed by Apple's Command Line Tools has this special scheme
+ that's used when:
+
+ * This is a framework build.
+ * We are installing into the system p... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/locations/_sysconfig.py |
Fully document this Python code with docstrings | import logging
import mimetypes
import os
from collections import defaultdict
from typing import Callable, Dict, Iterable, List, Optional, Tuple
from pip._vendor.packaging.utils import (
InvalidSdistFilename,
InvalidVersion,
InvalidWheelFilename,
canonicalize_name,
parse_sdist_filename,
parse_w... | --- +++ @@ -29,12 +29,15 @@ class LinkSource:
@property
def link(self) -> Optional[Link]:
+ """Returns the underlying link, if there's one."""
raise NotImplementedError()
def page_candidates(self) -> FoundCandidates:
+ """Candidates found by parsing an archive listing HTML file."... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/index/sources.py |
Add docstrings for production code | import logging
from typing import TYPE_CHECKING, Iterable, Optional, Set, Tuple
from pip._internal.build_env import BuildEnvironment
from pip._internal.distributions.base import AbstractDistribution
from pip._internal.exceptions import InstallationError
from pip._internal.metadata import BaseDistribution
from pip._int... | --- +++ @@ -14,9 +14,15 @@
class SourceDistribution(AbstractDistribution):
+ """Represents a source distribution.
+
+ The preparation step for these needs metadata for the packages to be
+ generated, either using PEP 517 or using the legacy `setup.py egg_info`.
+ """
@property
def build_trac... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/distributions/sdist.py |
Add docstrings that explain inputs and outputs | import importlib.metadata
import os
from typing import Any, Optional, Protocol, Tuple, cast
from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
class BadMetadata(ValueError):
def __init__(self, dist: importlib.metadata.Distribution, *, reason: str) -> None:
self.dist = dist
... | --- +++ @@ -15,6 +15,15 @@
class BasePath(Protocol):
+ """A protocol that various path objects conform.
+
+ This exists because importlib.metadata uses both ``pathlib.Path`` and
+ ``zipfile.Path``, and we need a common base for type hints (Union does not
+ work well since ``zipfile.Path`` is too new for... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/metadata/importlib/_compat.py |
Add missing documentation to my Python functions | import functools
import os
import site
import sys
import sysconfig
import typing
from pip._internal.exceptions import InstallationError
from pip._internal.utils import appdirs
from pip._internal.utils.virtualenv import running_under_virtualenv
# Application Directories
USER_CACHE_DIR = appdirs.user_cache_dir("pip")
... | --- +++ @@ -17,10 +17,22 @@
def get_major_minor_version() -> str:
+ """
+ Return the major-minor version of the current Python as a string, e.g.
+ "3.7" or "3.10".
+ """
return "{}.{}".format(*sys.version_info)
def change_root(new_root: str, pathname: str) -> str:
+ """Return 'pathname' wit... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/locations/base.py |
Write Python docstrings for this snippet | import contextlib
import functools
import os
import sys
from typing import TYPE_CHECKING, List, Optional, Type, cast
from pip._internal.utils.misc import strtobool
from .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel
if TYPE_CHECKING:
from typing import Literal, Protocol
else:... | --- +++ @@ -27,6 +27,19 @@
def _should_use_importlib_metadata() -> bool:
+ """Whether to use the ``importlib.metadata`` or ``pkg_resources`` backend.
+
+ By default, pip uses ``importlib.metadata`` on Python 3.11+, and
+ ``pkg_resourcess`` otherwise. This can be overridden by a couple of ways:
+
+ * If ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/metadata/__init__.py |
Auto-generate documentation strings for this file |
def hamming(n_element: int) -> list:
n_element = int(n_element)
if n_element < 1:
my_error = ValueError("a should be a positive number")
raise my_error
hamming_list = [1]
i, j, k = (0, 0, 0)
index = 1
while index < n_element:
while hamming_list[i] * 2 <= hamming_list[-... | --- +++ @@ -1,6 +1,25 @@+"""
+A Hamming number is a positive integer of the form 2^i*3^j*5^k, for some
+non-negative integers i, j, and k. They are often referred to as regular numbers.
+The first 20 Hamming numbers are: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, and 36
+"""
def hamming(n_... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/hamming-numbers.py |
Generate documentation strings for clarity |
from dataclasses import dataclass
SCHEME_KEYS = ["platlib", "purelib", "headers", "scripts", "data"]
@dataclass(frozen=True)
class Scheme:
__slots__ = SCHEME_KEYS
platlib: str
purelib: str
headers: str
scripts: str
data: str | --- +++ @@ -1,3 +1,9 @@+"""
+For types associated with installation schemes.
+
+For a general overview of available schemes and their context, see
+https://docs.python.org/3/install/index.html#alternate-installation.
+"""
from dataclasses import dataclass
@@ -6,6 +12,9 @@
@dataclass(frozen=True)
class Scheme:
+... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/models/scheme.py |
Add docstrings to existing functions |
import configparser
import contextlib
import locale
import logging
import pathlib
import re
import sys
from itertools import chain, groupby, repeat
from typing import TYPE_CHECKING, Dict, Iterator, List, Literal, Optional, Union
from pip._vendor.rich.console import Console, ConsoleOptions, RenderResult
from pip._vend... | --- +++ @@ -1,3 +1,9 @@+"""Exceptions used throughout package.
+
+This module MUST NOT try to import from anything within `pip._internal` to
+operate. This is expected to be importable from any/all files within the
+subpackage and, thus, should not depend on them.
+"""
import configparser
import contextlib
@@ -49,9... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/exceptions.py |
Document functions with detailed explanations | import email.message
import email.parser
import logging
import os
import zipfile
from typing import (
Collection,
Iterable,
Iterator,
List,
Mapping,
NamedTuple,
Optional,
)
from pip._vendor import pkg_resources
from pip._vendor.packaging.requirements import Requirement
from pip._vendor.pack... | --- +++ @@ -46,6 +46,10 @@
class InMemoryMetadata:
+ """IMetadataProvider that reads metadata files from a dictionary.
+
+ This also maps metadata decoding exceptions to our internal exception type.
+ """
def __init__(self, metadata: Mapping[str, bytes], wheel_name: str) -> None:
self._meta... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/metadata/pkg_resources.py |
Document this script properly |
# The following comment should be removed at some point in the future.
# mypy: strict-optional=False
# If pip's going to use distutils, it should not be using the copy that setuptools
# might have injected into the environment. This is done by removing the injected
# shim, if it's injected.
#
# See https://github.com... | --- +++ @@ -1,3 +1,4 @@+"""Locations where we look for configs, install stuff, etc"""
# The following comment should be removed at some point in the future.
# mypy: strict-optional=False
@@ -41,6 +42,9 @@ *,
ignore_config_files: bool = False,
) -> Dict[str, str]:
+ """
+ Return a distutils install s... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/locations/_distutils.py |
Write docstrings including parameters and return values | import csv
import email.message
import functools
import json
import logging
import pathlib
import re
import zipfile
from typing import (
IO,
Any,
Collection,
Container,
Dict,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
Protocol,
Tuple,
Union,
)
from pip._vendor.p... | --- +++ @@ -64,6 +64,23 @@ entry: Tuple[str, ...],
info: Tuple[str, ...],
) -> str:
+ """Convert a legacy installed-files.txt path into modern RECORD path.
+
+ The legacy format stores paths relative to the info directory, while the
+ modern format stores paths relative to the package root, e.g. the
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/metadata/base.py |
Generate NumPy-style docstrings | import functools
import itertools
import logging
import os
import posixpath
import re
import urllib.parse
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Mapping,
NamedTuple,
Optional,
Tuple,
Union,
)
from pip._internal.utils.deprecation import... | --- +++ @@ -42,6 +42,14 @@
@dataclass(frozen=True)
class LinkHash:
+ """Links to content may have embedded hash values. This class parses those.
+
+ `name` must be any member of `_SUPPORTED_HASHES`.
+
+ This class can be converted to and from `ArchiveInfo`. While ArchiveInfo intends to
+ be JSON-serializ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/models/link.py |
Add docstrings that explain purpose and usage | import functools
import importlib.metadata
import logging
import os
import pathlib
import sys
import zipfile
import zipimport
from typing import Iterator, List, Optional, Sequence, Set, Tuple
from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
from pip._internal.metadata.base import BaseDistribu... | --- +++ @@ -32,6 +32,17 @@
class _DistributionFinder:
+ """Finder to locate distributions.
+
+ The main purpose of this class is to memoize found distributions' names, so
+ only one distribution is returned for each package name. At lot of pip code
+ assumes this (because it is setuptools's behavior), a... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/metadata/importlib/_envs.py |
Generate docstrings for this script | import sys
from typing import List, Optional, Set, Tuple
from pip._vendor.packaging.tags import Tag
from pip._internal.utils.compatibility_tags import get_supported, version_info_to_nodot
from pip._internal.utils.misc import normalize_version_info
class TargetPython:
__slots__ = [
"_given_py_version_in... | --- +++ @@ -8,6 +8,10 @@
class TargetPython:
+ """
+ Encapsulates the properties of a Python interpreter one is targeting
+ for a package install, download, etc.
+ """
__slots__ = [
"_given_py_version_info",
@@ -27,6 +31,20 @@ abis: Optional[List[str]] = None,
implementa... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/models/target_python.py |
Write docstrings that follow conventions |
import json
import re
import urllib.parse
from dataclasses import dataclass
from typing import Any, ClassVar, Dict, Iterable, Optional, Type, TypeVar, Union
__all__ = [
"DirectUrl",
"DirectUrlValidationError",
"DirInfo",
"ArchiveInfo",
"VcsInfo",
]
T = TypeVar("T")
DIRECT_URL_METADATA_NAME = "di... | --- +++ @@ -1,3 +1,4 @@+""" PEP 610 """
import json
import re
@@ -26,6 +27,7 @@ def _get(
d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None
) -> Optional[T]:
+ """Get value from dictionary and verify expected type."""
if key not in d:
return default
value =... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/models/direct_url.py |
Generate docstrings with examples |
import re
from typing import Dict, Iterable, List
from pip._vendor.packaging.tags import Tag
from pip._internal.exceptions import InvalidWheelFilename
class Wheel:
wheel_file_re = re.compile(
r"""^(?P<namever>(?P<name>[^\s-]+?)-(?P<ver>[^\s-]*?))
((-(?P<build>\d[^-]*?))?-(?P<pyver>[^\s-]+?)-(?... | --- +++ @@ -1,3 +1,6 @@+"""Represents a wheel file and provides access to the various parts of the
+name that have meaning.
+"""
import re
from typing import Dict, Iterable, List
@@ -8,6 +11,7 @@
class Wheel:
+ """A wheel file"""
wheel_file_re = re.compile(
r"""^(?P<namever>(?P<name>[^\s-]+?)... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/models/wheel.py |
Write docstrings for backend logic |
import os
from contextlib import contextmanager
from datetime import datetime
from typing import BinaryIO, Generator, Optional, Union
from pip._vendor.cachecontrol.cache import SeparateBodyBaseCache
from pip._vendor.cachecontrol.caches import SeparateBodyFileCache
from pip._vendor.requests.models import Response
fro... | --- +++ @@ -1,3 +1,5 @@+"""HTTP cache implementation.
+"""
import os
from contextlib import contextmanager
@@ -18,6 +20,9 @@
@contextmanager
def suppressed_cache_errors() -> Generator[None, None, None]:
+ """If we can't access the cache then we can just skip caching and process
+ requests as if caching was... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/network/cache.py |
Document this code for team use | import itertools
import logging
import os
import posixpath
import urllib.parse
from dataclasses import dataclass
from typing import List
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.models.index import PyPI
from pip._internal.utils.compat import has_tls
from pip._internal.utils.misc im... | --- +++ @@ -17,6 +17,9 @@
@dataclass(frozen=True)
class SearchScope:
+ """
+ Encapsulates the locations that pip is configured to search.
+ """
__slots__ = ["find_links", "index_urls", "no_index"]
@@ -31,6 +34,9 @@ index_urls: List[str],
no_index: bool,
) -> "SearchScope":
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/models/search_scope.py |
Add docstrings to my Python code |
import enum
import functools
import itertools
import logging
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING, FrozenSet, Iterable, List, Optional, Set, Tuple, Union
from pip._vendor.packaging import specifiers
from pip._vendor.packaging.tags import Tag
from pip._vendor.packaging.utils imp... | --- +++ @@ -1,3 +1,4 @@+"""Routines related to PyPI, indexes"""
import enum
import functools
@@ -53,6 +54,15 @@ version_info: Tuple[int, int, int],
ignore_requires_python: bool = False,
) -> bool:
+ """
+ Return whether the given Python version is compatible with a link's
+ "Requires-Python" valu... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/index/package_finder.py |
Add docstrings to my Python code |
import email.message
import logging
import mimetypes
import os
from typing import Iterable, Optional, Tuple
from pip._vendor.requests.models import Response
from pip._internal.cli.progress_bars import get_download_progress_renderer
from pip._internal.exceptions import NetworkConnectionError
from pip._internal.models... | --- +++ @@ -1,3 +1,5 @@+"""Download files with progress indicators.
+"""
import email.message
import logging
@@ -69,10 +71,17 @@
def sanitize_content_filename(filename: str) -> str:
+ """
+ Sanitize the "filename" value from a Content-Disposition header.
+ """
return os.path.basename(filename)
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/network/download.py |
Generate descriptive docstrings automatically |
import os
from pip._vendor.pyproject_hooks import BuildBackendHookCaller
from pip._internal.build_env import BuildEnvironment
from pip._internal.exceptions import (
InstallationSubprocessError,
MetadataGenerationFailed,
)
from pip._internal.utils.subprocess import runner_with_spinner_message
from pip._intern... | --- +++ @@ -1,3 +1,5 @@+"""Metadata generation logic for source distributions.
+"""
import os
@@ -15,6 +17,10 @@ def generate_editable_metadata(
build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str
) -> str:
+ """Generate metadata using mechanisms described in PEP 660.
+
+ Returns... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/operations/build/metadata_editable.py |
Add docstrings that explain inputs and outputs |
import logging
import os
import shutil
import subprocess
import sysconfig
import typing
import urllib.parse
from abc import ABC, abstractmethod
from functools import lru_cache
from os.path import commonprefix
from pathlib import Path
from typing import Any, Dict, List, NamedTuple, Optional, Tuple
from pip._vendor.req... | --- +++ @@ -1,3 +1,8 @@+"""Network Authentication Helpers
+
+Contains interface (MultiDomainBasicAuth) and associated glue code for
+providing credentials in the context of network requests.
+"""
import logging
import os
@@ -38,6 +43,7 @@
class KeyRingBaseProvider(ABC):
+ """Keyring base provider interface""... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/network/auth.py |
Write docstrings including parameters and return values |
import os
from pip._vendor.pyproject_hooks import BuildBackendHookCaller
from pip._internal.build_env import BuildEnvironment
from pip._internal.exceptions import (
InstallationSubprocessError,
MetadataGenerationFailed,
)
from pip._internal.utils.subprocess import runner_with_spinner_message
from pip._intern... | --- +++ @@ -1,3 +1,5 @@+"""Metadata generation logic for source distributions.
+"""
import os
@@ -15,6 +17,10 @@ def generate_metadata(
build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str
) -> str:
+ """Generate metadata using mechanisms described in PEP 517.
+
+ Returns the gene... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/operations/build/metadata.py |
Add docstrings that explain logic |
import logging
import os
from pip._internal.build_env import BuildEnvironment
from pip._internal.cli.spinners import open_spinner
from pip._internal.exceptions import (
InstallationError,
InstallationSubprocessError,
MetadataGenerationFailed,
)
from pip._internal.utils.setuptools_build import make_setupto... | --- +++ @@ -1,3 +1,5 @@+"""Metadata generation logic for legacy source distributions.
+"""
import logging
import os
@@ -17,6 +19,7 @@
def _find_egg_info(directory: str) -> str:
+ """Find an .egg-info subdirectory in `directory`."""
filenames = [f for f in os.listdir(directory) if f.endswith(".egg-info")... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/operations/build/metadata_legacy.py |
Create simple docstrings for beginners |
import logging
from contextlib import suppress
from email.parser import Parser
from functools import reduce
from typing import (
Callable,
Dict,
FrozenSet,
Generator,
Iterable,
List,
NamedTuple,
Optional,
Set,
Tuple,
)
from pip._vendor.packaging.requirements import Requirement
... | --- +++ @@ -1,3 +1,5 @@+"""Validation of dependencies of packages
+"""
import logging
from contextlib import suppress
@@ -46,6 +48,7 @@
def create_package_set_from_installed() -> Tuple[PackageSet, bool]:
+ """Converts a list of distributions into a PackageSet."""
package_set = {}
problems = False
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/operations/check.py |
Write Python docstrings for this snippet | import contextlib
import hashlib
import logging
import os
from types import TracebackType
from typing import Dict, Generator, Optional, Type, Union
from pip._internal.req.req_install import InstallRequirement
from pip._internal.utils.temp_dir import TempDirectory
logger = logging.getLogger(__name__)
@contextlib.con... | --- +++ @@ -51,9 +51,17 @@
class TrackerId(str):
+ """Uniquely identifying string provided to the build tracker."""
class BuildTracker:
+ """Ensure that an sdist cannot request itself as a setup requirement.
+
+ When an sdist is prepared, it identifies its setup requirements in the
+ context of ``B... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/operations/build/build_tracker.py |
Write clean docstrings for readability |
import logging
import urllib.parse
import xmlrpc.client
from typing import TYPE_CHECKING, Tuple
from pip._internal.exceptions import NetworkConnectionError
from pip._internal.network.session import PipSession
from pip._internal.network.utils import raise_for_status
if TYPE_CHECKING:
from xmlrpc.client import _Ho... | --- +++ @@ -1,3 +1,5 @@+"""xmlrpclib.Transport implementation
+"""
import logging
import urllib.parse
@@ -17,6 +19,9 @@
class PipXmlrpcTransport(xmlrpc.client.Transport):
+ """Provide a `xmlrpclib.Transport` implementation via a `PipSession`
+ object.
+ """
def __init__(
self, index_url... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/network/xmlrpc.py |
Add docstrings with type hints explained |
import email.utils
import functools
import io
import ipaddress
import json
import logging
import mimetypes
import os
import platform
import shutil
import subprocess
import sys
import urllib.parse
import warnings
from typing import (
TYPE_CHECKING,
Any,
Dict,
Generator,
List,
Mapping,
Option... | --- +++ @@ -1,3 +1,6 @@+"""PipSession and supporting code, containing all pip-specific
+network request configuration and behavior.
+"""
import email.utils
import functools
@@ -95,6 +98,9 @@
def looks_like_ci() -> bool:
+ """
+ Return whether it looks like pip is running under CI.
+ """
# We don't... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/network/session.py |
Create docstrings for each class method |
import logging
from typing import Optional, Sequence
from pip._internal.build_env import BuildEnvironment
from pip._internal.utils.logging import indent_log
from pip._internal.utils.setuptools_build import make_setuptools_develop_args
from pip._internal.utils.subprocess import call_subprocess
logger = logging.getLog... | --- +++ @@ -1,3 +1,5 @@+"""Legacy editable installation process, i.e. `setup.py develop`.
+"""
import logging
from typing import Optional, Sequence
@@ -22,6 +24,9 @@ build_env: BuildEnvironment,
unpacked_source_directory: str,
) -> None:
+ """Install a package in editable mode. Most arguments are pass-... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/operations/install/editable_legacy.py |
Expand my code with proper documentation strings | import logging
import os.path
from typing import List, Optional
from pip._internal.cli.spinners import open_spinner
from pip._internal.utils.setuptools_build import make_setuptools_bdist_wheel_args
from pip._internal.utils.subprocess import call_subprocess, format_command_args
logger = logging.getLogger(__name__)
d... | --- +++ @@ -13,6 +13,7 @@ command_args: List[str],
command_output: str,
) -> str:
+ """Format command information for logging."""
command_desc = format_command_args(command_args)
text = f"Command arguments: {command_desc}\n"
@@ -35,6 +36,7 @@ command_args: List[str],
command_output: st... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/operations/build/wheel_legacy.py |
Add docstrings to improve collaboration |
__all__ = ["HTTPRangeRequestUnsupported", "dist_from_wheel_url"]
from bisect import bisect_left, bisect_right
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from typing import Any, Dict, Generator, List, Optional, Tuple
from zipfile import BadZipFile, ZipFile
from pip._vendor.packaging... | --- +++ @@ -1,3 +1,4 @@+"""Lazy ZIP over HTTP"""
__all__ = ["HTTPRangeRequestUnsupported", "dist_from_wheel_url"]
@@ -20,6 +21,13 @@
def dist_from_wheel_url(name: str, url: str, session: PipSession) -> BaseDistribution:
+ """Return a distribution object from the given wheel URL.
+
+ This uses HTTP range ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/network/lazy_wheel.py |
Add detailed docstrings explaining each function |
# The following comment should be removed at some point in the future.
# mypy: strict-optional=False
import mimetypes
import os
import shutil
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Iterable, List, Optional
from pip._vendor.packaging.utils import canonicalize_name
from pi... | --- +++ @@ -1,3 +1,5 @@+"""Prepares a distribution for installation
+"""
# The following comment should be removed at some point in the future.
# mypy: strict-optional=False
@@ -62,6 +64,7 @@ build_isolation: bool,
check_build_deps: bool,
) -> BaseDistribution:
+ """Prepare a distribution for installat... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/operations/prepare.py |
Add docstrings to clarify complex logic |
import collections
import compileall
import contextlib
import csv
import importlib
import logging
import os.path
import re
import shutil
import sys
import warnings
from base64 import urlsafe_b64encode
from email.message import Message
from itertools import chain, filterfalse, starmap
from typing import (
IO,
T... | --- +++ @@ -1,3 +1,5 @@+"""Support for installing and building the "wheel" binary package format.
+"""
import collections
import compileall
@@ -76,16 +78,23 @@
def rehash(path: str, blocksize: int = 1 << 20) -> Tuple[str, str]:
+ """Return (encoded_digest, length) for path using hashlib.sha256()"""
h, l... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/operations/install/wheel.py |
Document all endpoints with docstrings |
import logging
import optparse
import os
import re
import shlex
import urllib.parse
from optparse import Values
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Iterable,
List,
NoReturn,
Optional,
Tuple,
)
from pip._internal.cli import cmdoptions
from pip._in... | --- +++ @@ -1,3 +1,6 @@+"""
+Requirements file parsing
+"""
import logging
import optparse
@@ -133,6 +136,15 @@ options: Optional[optparse.Values] = None,
constraint: bool = False,
) -> Generator[ParsedRequirement, None, None]:
+ """Parse a requirements file and yield ParsedRequirement instances.
+
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/req/req_file.py |
Add docstrings to clarify complex logic |
import copy
import logging
import os
import re
from dataclasses import dataclass
from typing import Collection, Dict, List, Optional, Set, Tuple, Union
from pip._vendor.packaging.markers import Marker
from pip._vendor.packaging.requirements import InvalidRequirement, Requirement
from pip._vendor.packaging.specifiers ... | --- +++ @@ -1,3 +1,12 @@+"""Backing implementation for InstallRequirement's various constructors
+
+The idea here is that these formed a major chunk of InstallRequirement's size
+so, moving them and support code dedicated to them outside of that class
+helps creates for better understandability for the rest of the code... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/req/constructors.py |
Generate helpful docstrings for debugging | import functools
import os
import sys
import sysconfig
from importlib.util import cache_from_source
from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Set, Tuple
from pip._internal.exceptions import LegacyDistutilsInstall, UninstallMissingRecord
from pip._internal.locations import get_bin_pre... | --- +++ @@ -21,6 +21,10 @@ def _script_names(
bin_dir: str, script_name: str, is_gui: bool
) -> Generator[str, None, None]:
+ """Create the fully qualified name of the files created by
+ {console,gui}_scripts for the given ``dist``.
+ Returns the list of file names
+ """
exe_name = os.path.join(b... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/req/req_uninstall.py |
Add docstrings to meet PEP guidelines |
import logging
import sys
from collections import defaultdict
from itertools import chain
from typing import DefaultDict, Iterable, List, Optional, Set, Tuple
from pip._vendor.packaging import specifiers
from pip._vendor.packaging.requirements import Requirement
from pip._internal.cache import WheelCache
from pip._i... | --- +++ @@ -1,3 +1,14 @@+"""Dependency Resolution
+
+The dependency resolution in pip is performed as follows:
+
+for top-level requirements:
+ a. only one spec allowed per project, regardless of conflicts or not.
+ otherwise a "double requirement" exception is raised
+ b. they override sub-dependency requi... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/resolution/legacy/resolver.py |
Document this module using docstrings | import functools
import logging
import os
import shutil
import sys
import uuid
import zipfile
from optparse import Values
from pathlib import Path
from typing import Any, Collection, Dict, Iterable, List, Optional, Sequence, Union
from pip._vendor.packaging.markers import Marker
from pip._vendor.packaging.requirements... | --- +++ @@ -63,6 +63,11 @@
class InstallRequirement:
+ """
+ Represents something that may be installed later on, may have information
+ about where to fetch the relevant requirement and also contains logic for
+ installing the said requirement.
+ """
def __init__(
self,
@@ -223,6 +22... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/req/req_install.py |
Add docstrings to incomplete code | from dataclasses import dataclass
from typing import FrozenSet, Iterable, Optional, Tuple
from pip._vendor.packaging.specifiers import SpecifierSet
from pip._vendor.packaging.utils import NormalizedName
from pip._vendor.packaging.version import Version
from pip._internal.models.link import Link, links_equivalent
from... | --- +++ @@ -60,10 +60,21 @@ class Requirement:
@property
def project_name(self) -> NormalizedName:
+ """The "project name" of a requirement.
+
+ This is different from ``name`` if this requirement contains extras,
+ in which case ``name`` would contain the ``[...]`` part, while this
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/base.py |
Add concise docstrings to each method | import logging
import sys
from typing import TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Tuple, Union, cast
from pip._vendor.packaging.requirements import InvalidRequirement
from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
from pip._vendor.packaging.version import Version
from pip._int... | --- +++ @@ -41,6 +41,7 @@
def as_base_candidate(candidate: Candidate) -> Optional[BaseCandidate]:
+ """The runtime version of BaseCandidate."""
base_candidate_classes = (
AlreadyInstalledCandidate,
EditableCandidate,
@@ -121,6 +122,20 @@
class _InstallRequirementBackedCandidate(Candida... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/candidates.py |
Add docstrings to my Python code | from typing import Any, Optional
from pip._vendor.packaging.specifiers import SpecifierSet
from pip._vendor.packaging.utils import NormalizedName, canonicalize_name
from pip._internal.req.constructors import install_req_drop_extras
from pip._internal.req.req_install import InstallRequirement
from .base import Candid... | --- +++ @@ -120,6 +120,10 @@
class SpecifierWithoutExtrasRequirement(SpecifierRequirement):
+ """
+ Requirement backed by an install requirement on a base package.
+ Trims extras from its install requirement if there are any.
+ """
def __init__(self, ireq: InstallRequirement) -> None:
as... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/requirements.py |
Document this script properly |
import functools
import logging
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, Set, Tuple
from pip._vendor.packaging.version import _BaseVersion
from pip._internal.exceptions import MetadataInvalid
from .base import Candidate
logger = logging.getLogger(__n... | --- +++ @@ -1,3 +1,12 @@+"""Utilities to lazily create and visit candidates found.
+
+Creating and visiting a candidate is a *very* costly operation. It involves
+fetching, extracting, potentially building modules from source, and verifying
+distribution metadata. It is therefore crucial for performance to keep
+everyt... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py |
Write docstrings that follow conventions | import contextlib
import functools
import logging
from typing import (
TYPE_CHECKING,
Callable,
Dict,
FrozenSet,
Iterable,
Iterator,
List,
Mapping,
NamedTuple,
Optional,
Protocol,
Sequence,
Set,
Tuple,
TypeVar,
cast,
)
from pip._vendor.packaging.requireme... | --- +++ @@ -274,6 +274,7 @@ extras |= frozenset(ireq.extras)
def _get_installed_candidate() -> Optional[Candidate]:
+ """Get the candidate for the currently-installed version."""
# If --force-reinstall is set, we want the version from the index
# instead, so w... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/factory.py |
Add verbose docstrings with examples | import datetime
import functools
import hashlib
import json
import logging
import optparse
import os.path
import sys
from dataclasses import dataclass
from typing import Any, Callable, Dict, Optional
from pip._vendor.packaging.version import Version
from pip._vendor.packaging.version import parse as parse_version
from... | --- +++ @@ -40,6 +40,11 @@
def _convert_date(isodate: str) -> datetime.datetime:
+ """Convert an ISO format string to a date.
+
+ Handles the format 2020-01-22T14:24:01Z (trailing Z)
+ which is not supported by older versions of fromisoformat.
+ """
return datetime.datetime.fromisoformat(isodate.re... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/self_outdated_check.py |
Auto-generate documentation strings for this file | import contextlib
import functools
import logging
import os
from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, cast
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.resolvelib import BaseReporter, ResolutionImpossible
from pip._vendor.resolvelib import Resolver as RLResolver
... | --- +++ @@ -185,6 +185,18 @@ def get_installation_order(
self, req_set: RequirementSet
) -> List[InstallRequirement]:
+ """Get order for installation of requirements in RequirementSet.
+
+ The returned list contains a requirement before another that depends on
+ it. This helps ens... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/resolver.py |
Can you add docstrings to this Python file? |
import re
from typing import List, Optional, Tuple
from pip._vendor.packaging.tags import (
PythonVersion,
Tag,
compatible_tags,
cpython_tags,
generic_tags,
interpreter_name,
interpreter_version,
mac_platforms,
)
_osx_arch_pat = re.compile(r"(.+)_(\d+)_(\d+)_(.+)")
def version_info_... | --- +++ @@ -1,3 +1,5 @@+"""Generate and work with PEP 425 Compatibility Tags.
+"""
import re
from typing import List, Optional, Tuple
@@ -113,6 +115,18 @@ impl: Optional[str] = None,
abis: Optional[List[str]] = None,
) -> List[Tag]:
+ """Return a list of supported tags for each version specified in
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/compatibility_tags.py |
Add concise docstrings to each method | import os
import sys
from typing import Optional, Tuple
def glibc_version_string() -> Optional[str]:
return glibc_version_string_confstr() or glibc_version_string_ctypes()
def glibc_version_string_confstr() -> Optional[str]:
# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
# to ... | --- +++ @@ -4,10 +4,12 @@
def glibc_version_string() -> Optional[str]:
+ "Returns glibc version string, or None if not using glibc."
return glibc_version_string_confstr() or glibc_version_string_ctypes()
def glibc_version_string_confstr() -> Optional[str]:
+ "Primary implementation of glibc_version_... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/glibc.py |
Add docstrings for production code | import itertools
import os
import shutil
import sys
from typing import List, Optional
from pip._internal.cli.main import main
from pip._internal.utils.compat import WINDOWS
_EXECUTABLE_NAMES = [
"pip",
f"pip{sys.version_info.major}",
f"pip{sys.version_info.major}.{sys.version_info.minor}",
]
if WINDOWS:
... | --- +++ @@ -21,6 +21,17 @@
def _wrapper(args: Optional[List[str]] = None) -> int:
+ """Central wrapper for all old entrypoints.
+
+ Historically pip has had several entrypoints defined. Because of issues
+ arising from PATH, sys.path, multiple Pythons, their interactions, and most
+ of them having a pip... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/entrypoints.py |
Add detailed documentation for each class | import argparse
import hashlib # hashlib is only used inside the Test class
import struct
import unittest
class SHA1Hash:
def __init__(self, data):
self.data = data
self.h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
@staticmethod
def rotate(n, b):
return ((n <... | --- +++ @@ -5,33 +5,63 @@
class SHA1Hash:
+ """
+ Class to contain the entire pipeline for SHA1 Hashing Algorithm
+ """
def __init__(self, data):
+ """
+ Inititates the variables data and h. h is a list of 5 8-digit Hexadecimal
+ numbers corresponding to (1732584193, 4023233417,... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/sha1.py |
Include argument descriptions in docstrings | import tkinter as tk
class OneRepMaxCalculator:
def __init__(self):
self.window = tk.Tk()
self.window.title("One-Rep Max Calculator")
self.window.geometry("300x150")
# Create and pack widgets
tk.Label(self.window, text="Enter the weight you lifted (in kg):").pack()
... | --- +++ @@ -2,8 +2,32 @@
class OneRepMaxCalculator:
+ """
+ A class used to calculate the estimated one-repetition maximum (1RM) for a weightlifting exercise.
+
+ Attributes
+ ----------
+ window : tk.Tk
+ The main window of the application.
+ weight_entry : tk.Entry
+ Entry field to... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/nitkarshchourasia/to_sort/one_rep_max_calculator/one_rep_max_calculator_gui.py |
Add docstrings that explain purpose and usage | import errno
import getpass
import hashlib
import logging
import os
import posixpath
import shutil
import stat
import sys
import sysconfig
import urllib.parse
from dataclasses import dataclass
from functools import partial
from io import StringIO
from itertools import filterfalse, tee, zip_longest
from pathlib import P... | --- +++ @@ -80,6 +80,16 @@
def normalize_version_info(py_version_info: Tuple[int, ...]) -> Tuple[int, int, int]:
+ """
+ Convert a tuple of ints representing a Python version to one of length
+ three.
+
+ :param py_version_info: a tuple of ints representing a Python version,
+ or None to specify ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/misc.py |
Add docstrings to meet PEP guidelines |
import logging
from typing import Any, cast
# custom log level for `--verbose` output
# between DEBUG and INFO
VERBOSE = 15
class VerboseLogger(logging.Logger):
def verbose(self, msg: str, *args: Any, **kwargs: Any) -> None:
return self.log(VERBOSE, msg, *args, **kwargs)
def getLogger(name: str) -> V... | --- +++ @@ -1,3 +1,9 @@+"""Customize logging
+
+Defines custom logger class for the `logger.verbose(...)` method.
+
+init_logging() must be called before any other modules that call logging.getLogger.
+"""
import logging
from typing import Any, cast
@@ -8,15 +14,25 @@
class VerboseLogger(logging.Logger):
+ "... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/_log.py |
Help me document legacy Python code | import contextlib
import errno
import logging
import logging.handlers
import os
import sys
import threading
from dataclasses import dataclass
from io import TextIOWrapper
from logging import Filter
from typing import Any, ClassVar, Generator, List, Optional, TextIO, Type
from pip._vendor.rich.console import (
Cons... | --- +++ @@ -33,6 +33,9 @@
class BrokenStdoutLoggingError(Exception):
+ """
+ Raised if BrokenPipeError occurs for the stdout stream while logging.
+ """
def _is_broken_pipe_error(exc_class: Type[BaseException], exc: BaseException) -> bool:
@@ -50,6 +53,10 @@
@contextlib.contextmanager
def indent_lo... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/logging.py |
Generate docstrings for this script |
import importlib.resources
import logging
import os
import sys
from typing import IO
__all__ = ["get_path_uid", "stdlib_pkgs", "WINDOWS"]
logger = logging.getLogger(__name__)
def has_tls() -> bool:
try:
import _ssl # noqa: F401 # ignore unused
return True
except ImportError:
pas... | --- +++ @@ -1,3 +1,5 @@+"""Stuff that differs in different Python versions and platform
+distributions."""
import importlib.resources
import logging
@@ -25,6 +27,17 @@
def get_path_uid(path: str) -> int:
+ """
+ Return path's uid.
+
+ Does not follow symlinks:
+ https://github.com/pypa/pip/pull/... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/compat.py |
Create documentation strings for testing functions | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def replacetext(text: str) -> str:
return text.replace(" ", "-")
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input: str = input("Enter a text to replace spaces with hyphens: ")
print("The changed text is:", replacetext(user_inp... | --- +++ @@ -1,8 +1,30 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+Replace all spaces in a string with hyphens.
+
+Example:
+ >>> replacetext("Hello World")
+ 'Hello-World'
+ >>> replacetext("Python 3.13 is fun")
+ 'Python-3.13-is-fun'
+"""
def replacetext(text: str) -> str:
+ """
+ R... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/replacetext.py |
Can you add docstrings to this Python file? |
import functools
import itertools
def _nonblank(str):
return str and not str.startswith("#")
@functools.singledispatch
def yield_lines(iterable):
return itertools.chain.from_iterable(map(yield_lines, iterable))
@yield_lines.register(str)
def _(text):
return filter(_nonblank, map(str.strip, text.split... | --- +++ @@ -1,3 +1,33 @@+"""Functions brought over from jaraco.text.
+
+These functions are not supposed to be used within `pip._internal`. These are
+helper functions brought over from `jaraco.text` to enable vendoring newer
+copies of `pkg_resources` without having to vendor `jaraco.text` and its entire
+dependency c... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/_jaraco_text.py |
Create structured documentation for my script | import logging
import os
import shlex
import subprocess
from typing import Any, Callable, Iterable, List, Literal, Mapping, Optional, Union
from pip._vendor.rich.markup import escape
from pip._internal.cli.spinners import SpinnerInterface, open_spinner
from pip._internal.exceptions import InstallationSubprocessError
... | --- +++ @@ -15,6 +15,9 @@
def make_command(*args: Union[str, HiddenText, CommandArgs]) -> CommandArgs:
+ """
+ Create a CommandArgs object.
+ """
command_args: CommandArgs = []
for arg in args:
# Check for list instead of CommandArgs since CommandArgs is
@@ -29,6 +32,9 @@
def format_... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/subprocess.py |
Annotate my code with docstrings | import logging
import os
import re
from typing import List, Optional, Tuple
from pip._internal.utils.misc import (
HiddenText,
display_path,
is_console_interactive,
is_installable_dir,
split_auth_from_netloc,
)
from pip._internal.utils.subprocess import CommandArgs, make_command
from pip._internal.... | --- +++ @@ -43,6 +43,9 @@
@classmethod
def get_revision(cls, location: str) -> str:
+ """
+ Return the maximum revision for all files under a given location
+ """
# Note: taken from setuptools.command.egg_info
revision = 0
@@ -71,6 +74,10 @@ def get_netloc_and_aut... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/vcs/subversion.py |
Create documentation for each function signature |
import logging
import os
import shutil
import sys
import urllib.parse
from dataclasses import dataclass, field
from typing import (
Any,
Dict,
Iterable,
Iterator,
List,
Literal,
Mapping,
Optional,
Tuple,
Type,
Union,
)
from pip._internal.cli.spinners import SpinnerInterface... | --- +++ @@ -1,3 +1,4 @@+"""Handles all VCS (version control) support"""
import logging
import os
@@ -47,6 +48,9 @@
def is_url(name: str) -> bool:
+ """
+ Return true if the name looks like a URL.
+ """
scheme = urllib.parse.urlsplit(name).scheme
if not scheme:
return False
@@ -56,6 +... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/vcs/versioncontrol.py |
Generate docstrings with examples | import errno
import itertools
import logging
import os.path
import tempfile
import traceback
from contextlib import ExitStack, contextmanager
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
Generator,
List,
Optional,
TypeVar,
Union,
)
from pip._internal.utils.misc imp... | --- +++ @@ -48,14 +48,21 @@
class TempDirectoryTypeRegistry:
+ """Manages temp directory behavior"""
def __init__(self) -> None:
self._should_delete: Dict[str, bool] = {}
def set_delete(self, kind: str, value: bool) -> None:
+ """Indicate whether a TempDirectory of the given kind sh... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/temp_dir.py |
Document helper functions with docstrings |
import logging
import os
import shutil
import stat
import sys
import tarfile
import zipfile
from typing import Iterable, List, Optional
from zipfile import ZipInfo
from pip._internal.exceptions import InstallationError
from pip._internal.utils.filetypes import (
BZ2_EXTENSIONS,
TAR_EXTENSIONS,
XZ_EXTENSIO... | --- +++ @@ -1,3 +1,5 @@+"""Utilities related archives.
+"""
import logging
import os
@@ -40,6 +42,7 @@
def current_umask() -> int:
+ """Get the current umask which involves having to set it temporarily."""
mask = os.umask(0)
os.umask(mask)
return mask
@@ -58,6 +61,8 @@
def has_leading_dir(... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/unpacking.py |
Write docstrings for algorithm functions | import logging
import os
import re
import site
import sys
from typing import List, Optional
logger = logging.getLogger(__name__)
_INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile(
r"include-system-site-packages\s*=\s*(?P<value>true|false)"
)
def _running_under_venv() -> bool:
return sys.prefix != getattr(sys,... | --- +++ @@ -12,19 +12,32 @@
def _running_under_venv() -> bool:
+ """Checks if sys.base_prefix and sys.prefix match.
+
+ This handles PEP 405 compliant virtual environments.
+ """
return sys.prefix != getattr(sys, "base_prefix", sys.prefix)
def _running_under_legacy_virtualenv() -> bool:
+ """C... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/virtualenv.py |
Provide clean and structured docstrings | # SPDX-FileCopyrightText: 2015 Eric Larson
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import functools
import types
import zlib
from typing import TYPE_CHECKING, Any, Collection, Mapping
from pip._vendor.requests.adapters import HTTPAdapter
from pip._vendor.cachecontrol.cache import D... | --- +++ @@ -57,6 +57,10 @@ proxies: Mapping[str, str] | None = None,
cacheable_methods: Collection[str] | None = None,
) -> Response:
+ """
+ Send a request. Use the request information to see if it
+ exists in the cache and cache the response if we need to and can.
+ "... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/cachecontrol/adapter.py |
Generate docstrings for exported functions |
import logging
import os.path
import re
import shutil
from typing import Iterable, List, Optional, Tuple
from pip._vendor.packaging.utils import canonicalize_name, canonicalize_version
from pip._vendor.packaging.version import InvalidVersion, Version
from pip._internal.cache import WheelCache
from pip._internal.exce... | --- +++ @@ -1,3 +1,5 @@+"""Orchestrator for building wheels from InstallRequirements.
+"""
import logging
import os.path
@@ -33,6 +35,10 @@
def _contains_egg_info(s: str) -> bool:
+ """Determine whether the string looks like an egg_info.
+
+ :param s: The string to parse. E.g. foo-2.1
+ """
return... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/wheel_builder.py |
Fully document this Python code with docstrings | import configparser
import logging
import os
from typing import List, Optional, Tuple
from pip._internal.exceptions import BadCommand, InstallationError
from pip._internal.utils.misc import HiddenText, display_path
from pip._internal.utils.subprocess import make_command
from pip._internal.utils.urls import path_to_url... | --- +++ @@ -90,6 +90,9 @@
@classmethod
def get_revision(cls, location: str) -> str:
+ """
+ Return the repository-local changeset revision number, as an integer.
+ """
current_revision = cls.run_command(
["parents", "--template={rev}"],
show_stdout=Fals... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/vcs/mercurial.py |
Create structured documentation for my script | import logging
import os.path
import pathlib
import re
import urllib.parse
import urllib.request
from dataclasses import replace
from typing import List, Optional, Tuple
from pip._internal.exceptions import BadCommand, InstallationError
from pip._internal.utils.misc import HiddenText, display_path, hide_url
from pip._... | --- +++ @@ -106,6 +106,10 @@
@classmethod
def get_current_branch(cls, location: str) -> Optional[str]:
+ """
+ Return the current branch, or None if HEAD isn't at a branch
+ (e.g. detached HEAD).
+ """
# git-symbolic-ref exits with empty stdout if "HEAD" is a detached
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/vcs/git.py |
Provide clean and structured docstrings | # SPDX-FileCopyrightText: 2015 Eric Larson
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import calendar
import logging
import re
import time
from email.utils import parsedate_tz
from typing import TYPE_CHECKING, Collection, Mapping
from pip._vendor.requests.structures import CaseInsensi... | --- +++ @@ -2,6 +2,9 @@ #
# SPDX-License-Identifier: Apache-2.0
+"""
+The httplib2 algorithms ported for use with requests.
+"""
from __future__ import annotations
import calendar
@@ -32,6 +35,10 @@
def parse_uri(uri: str) -> tuple[str, str, str, str, str]:
+ """Parses a URI using the regex given in Appen... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/cachecontrol/controller.py |
Add documentation for all methods | # SPDX-FileCopyrightText: 2015 Eric Larson
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import hashlib
import os
from textwrap import dedent
from typing import IO, TYPE_CHECKING, Union
from pathlib import Path
from pip._vendor.cachecontrol.cache import BaseCache, SeparateBodyBaseCache
fr... | --- +++ @@ -60,6 +60,7 @@
class _FileCacheMixin:
+ """Shared implementation for both FileCache variants."""
def __init__(
self,
@@ -117,6 +118,9 @@ self._write(name, value)
def _write(self, path: str, data: bytes) -> None:
+ """
+ Safely write the data to the given pa... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/file_cache.py |
Turn comments into proper docstrings | # SPDX-FileCopyrightText: 2015 Eric Larson
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from datetime import datetime, timezone
from typing import TYPE_CHECKING
from pip._vendor.cachecontrol.cache import BaseCache
if TYPE_CHECKING:
from redis import Redis
class RedisCache(BaseCac... | --- +++ @@ -38,8 +38,11 @@ self.conn.delete(key)
def clear(self) -> None:
+ """Helper for clearing all the keys in a database. Use with
+ caution!"""
for key in self.conn.keys():
self.conn.delete(key)
def close(self) -> None:
- pass+ """Redis uses ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py |
Write docstrings for algorithm functions | # SPDX-FileCopyrightText: 2015 Eric Larson
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from threading import Lock
from typing import IO, TYPE_CHECKING, MutableMapping
if TYPE_CHECKING:
from datetime import datetime
class BaseCache:
def get(self, key: str) -> bytes | None:
... | --- +++ @@ -2,6 +2,10 @@ #
# SPDX-License-Identifier: Apache-2.0
+"""
+The cache object API for implementing caches. The default is a thread
+safe in-memory dictionary.
+"""
from __future__ import annotations
from threading import Lock
@@ -48,9 +52,23 @@
class SeparateBodyBaseCache(BaseCache):
+ """
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/cachecontrol/cache.py |
Write clean docstrings for readability |
from typing import List, Optional
def two_sum(nums: List[int], target: int) -> Optional[List[int]]:
if len(nums) < 2:
raise ValueError("Input list must contain at least two numbers.")
if not all(isinstance(num, int) for num in nums):
raise TypeError("All elements in the list must be integers... | --- +++ @@ -1,8 +1,34 @@+"""
+Author: Anurag Kumar (mailto:anuragkumarak95@gmail.com)
+
+Description:
+ This function finds two numbers in a given list that add up to a specified target.
+ It returns the indices of those two numbers.
+
+Constraints:
+ - Each input will have exactly one solution.
+ - The sam... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/two_num.py |
Write reusable docstrings | #
# Copyright (C) 2012-2023 The Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
import codecs
from collections import deque
import contextlib
import csv
from glob import iglob as std_iglob
import io
import json
import logging
import os
import py_compile
import re
import socket
try:
import ssl
... | --- +++ @@ -54,6 +54,14 @@
def parse_marker(marker_string):
+ """
+ Parse a marker string and return a dictionary containing a marker expression.
+
+ The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in
+ the expression grammar, or strings. A string contained in quotes is to be
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/util.py |
Write docstrings describing each step | import functools
import logging
import os
import pathlib
import sys
import sysconfig
from typing import Any, Dict, Generator, Optional, Tuple
from pip._internal.models.scheme import SCHEME_KEYS, Scheme
from pip._internal.utils.compat import WINDOWS
from pip._internal.utils.deprecation import deprecated
from pip._inter... | --- +++ @@ -44,6 +44,16 @@
def _should_use_sysconfig() -> bool:
+ """This function determines the value of _USE_SYSCONFIG.
+
+ By default, pip uses sysconfig on Python 3.10+.
+ But Python distributors can override this decision by setting:
+ sysconfig._PIP_USE_SYSCONFIG = True / False
+ Rationale... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/locations/__init__.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.