### Set up Local Development Environment (uv) Source: https://github.com/python/typeshed/blob/main/CONTRIBUTING.md Commands to set up a Python virtual environment and install test dependencies using uv, a fast Python package installer. This method is an alternative to pip. ```shell uv venv uv pip install -r requirements-tests.txt ``` -------------------------------- ### Set up Local Development Environment (Bash) Source: https://github.com/python/typeshed/blob/main/CONTRIBUTING.md Commands to set up a Python virtual environment and install test dependencies using pip for Linux, macOS, or WSL. ```bash python3 -m venv .venv source .venv/bin/activate (.venv)$ pip install -U pip (.venv)$ pip install -r requirements-tests.txt ``` -------------------------------- ### Example: Testing `requests` Stub Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md An example demonstrating where test cases for a third-party library stub, such as `requests`, would be located within the typeshed repository structure. ```shell stubs/requests/@tests/test_cases/ ``` -------------------------------- ### Get Help for Regression Test Script Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md Displays the help message for the `regr_test.py` script, outlining all available command-line options for running regression tests. ```shell python tests/regr_test.py -h ``` -------------------------------- ### Set up Local Development Environment (Windows PowerShell) Source: https://github.com/python/typeshed/blob/main/CONTRIBUTING.md Commands to set up a Python virtual environment and install test dependencies using pip for Windows. Note the different activation script path. ```powershell py -m venv .venv .venv\Scripts\activate (.venv) > python -m pip install -U pip (.venv) > pip install -r requirements-tests.txt ``` -------------------------------- ### Install Third-Party Type Stubs using pip Source: https://context7.com/python/typeshed/llms.txt Installs type stubs for third-party Python packages from PyPI. Supports individual packages, multiple packages, and version-specific installations. ```bash # Install stubs for the requests library pip install types-requests # Install stubs for multiple packages pip install types-html5lib types-requests types-PyYAML # Install specific version compatible with urllib3 v1.x pip install "types-requests<2.31.0.7" ``` -------------------------------- ### Example: Testing `ExitStack` Idiomatic Usage Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md An example test case file (`check_contextlib.py`) in `stdlib/@tests/test_cases/` that ensures type checkers do not produce false positives for idiomatic usage of the `ExitStack` class. ```python # stdlib/@tests/test_cases/check_contextlib.py # ... contains samples for ExitStack ... ``` -------------------------------- ### Example: Testing `LogRecord` Idiomatic Usage Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md An example test case file (`check_logging.py`) in `stdlib/@tests/test_cases/` that verifies that type checkers correctly handle idiomatic usage patterns of the `LogRecord` class without emitting unnecessary errors. ```python # stdlib/@tests/test_cases/check_logging.py # ... contains samples for LogRecord ... ``` -------------------------------- ### Generate Stub Files with stubgen (Bash) Source: https://github.com/python/typeshed/blob/main/CONTRIBUTING.md Uses the stubgen tool to automatically generate initial stub files for a given Python library. It requires the library to be installed in the current virtual environment. ```bash (.venv)$ pip install $INSERT_LIBRARY_NAME_HERE (.venv)$ python3 scripts/create_baseline_stubs.py $INSERT_LIBRARY_NAME_HERE ``` -------------------------------- ### Example: Checking `pow` Function Type Annotations Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md An example test case file (`check_pow.py`) located in `stdlib/@tests/test_cases/builtins/` that verifies type checker understanding of complex type annotations for the `pow` function. ```python # stdlib/@tests/test_cases/builtins/check_pow.py # ... contains code to test pow function type annotations ... ``` -------------------------------- ### Example: Checking `asyncio.gather` Type Annotations Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md An example test case file (`check_gather.py`) located in `stdlib/@tests/test_cases/asyncio/` that checks if a type checker correctly interprets the type annotations for `asyncio.gather`. ```python # stdlib/@tests/test_cases/asyncio/check_gather.py # ... contains code to test asyncio.gather type annotations ... ``` -------------------------------- ### Run Pyright Tests on Typeshed Stubs with Python Source: https://github.com/python/typeshed/blob/main/tests/README.md This test uses Pyright, a fast type checker, to validate Typeshed stubs. It requires Node.js to be installed. The script can check all files, a specific file, or use a stricter configuration file for more thorough checks. The stricter configuration is used in Typeshed's CI. ```bash (.venv3)$ python3 tests/pyright_test.py # Check all files (.venv3)$ python3 tests/pyright_test.py stdlib/sys.pyi # Check one file (.venv3)$ python3 tests/pyright_test.py -p pyrightconfig.stricter.json # Check with the stricter config. ``` -------------------------------- ### Install Third-Party Python Type Stubs Source: https://github.com/python/typeshed/blob/main/README.md Installs type stub packages for third-party Python libraries using pip. These packages adhere to PEP 561 and are automatically released. This command is useful for users of type checkers who need stubs for libraries not included in the standard library. ```bash $ pip install types-html5lib types-requests ``` -------------------------------- ### Manage External Stub Dependencies with Python Script Source: https://github.com/python/typeshed/blob/main/tests/README.md This script helps manage external dependencies required by third-party stubs in Typeshed. It can list dependencies for specific stubs or all stubs, and can be used in conjunction with other scripts to install them. Ensure you are in a Python virtual environment before running. ```bash (.venv3)$ python tests/get_external_stub_requirements.py # List external dependencies for (.venv3)$ python tests/get_external_stub_requirements.py # List external dependencies for and (.venv3)$ python tests/get_external_stub_requirements.py # List external dependencies for all third-party stubs in typeshed (.venv3)$ python scripts/install_all_third_party_dependencies.py # Install external dependencies for all third-party stubs in typeshed ``` -------------------------------- ### Creating a Stub File (Python) Source: https://context7.com/python/typeshed/llms.txt Define type stubs for Python functions, classes, and overloaded functions. This example shows annotations for simple functions, overloaded functions, class attributes, methods, and generic types. ```python # stubs/mypackage/mypackage/__init__.pyi from typing import Any, overload from typing_extensions import Literal def simple_function(x: int, y: str) -> bool: ... @overload def overloaded_func(x: int) -> int: ... @overload def overloaded_func(x: str) -> str: ... class MyClass: attribute: str def __init__(self, value: str) -> None: ... def method(self, x: int, *, flag: bool = False) -> list[str]: ... def accepts_literal(mode: Literal["r", "w", "a"]) -> None: ... # Generic type annotation def process_items(items: list[dict[str, Any]]) -> dict[str, list[int]]: ... ``` -------------------------------- ### Validate Standard Library Stubs using stubtest Source: https://context7.com/python/typeshed/llms.txt Runs stubtest to compare Python standard library stubs against actual runtime objects. Requires activating a virtual environment and installing test dependencies. ```bash # Activate virtual environment python3 -m venv .venv source .venv/bin/activate # Install test dependencies pip install -r requirements-tests.txt # Run stubtest for standard library python3 tests/stubtest_stdlib.py # Run stubtest for specific Python version # Output depends on your Python version and platform ``` -------------------------------- ### Import OS-Specific Serial Modules (Python) Source: https://github.com/python/typeshed/blob/main/stubs/pyserial/@tests/stubtest_allowlist_win32.txt This snippet demonstrates the import of serial modules that are specific to certain operating systems. It highlights potential import errors if these modules are accessed on incompatible platforms. No external dependencies are required beyond the standard Python installation. ```python import serial.serialposix # Posix only import serial.tools.list_ports_osx # Mac only import serial.tools.list_ports_posix # Posix only ``` -------------------------------- ### Validate Third-Party Stubs using stubtest Source: https://context7.com/python/typeshed/llms.txt Tests third-party Python stubs against their installed runtime packages. This command can check all third-party stubs or specific distributions. ```bash # Check all third-party stubs (downloads from PyPI) python3 tests/stubtest_third_party.py # Check specific distributions only python3 tests/stubtest_third_party.py requests toml ``` -------------------------------- ### Parsing VERSIONS File (Python) Source: https://context7.com/python/typeshed/llms.txt Determine Python version support for stdlib modules by parsing the VERSIONS file. This Python code snippet demonstrates how to get version information for specific modules and submodules. ```python from ts_utils.utils import parse_stdlib_versions_file, supported_versions_for_module # Parse stdlib/VERSIONS file versions = parse_stdlib_versions_file() # Check specific module if "asyncio" in versions: min_ver, max_ver = versions["asyncio"] print(f"asyncio: {min_ver[0]}.{min_ver[1]} - {max_ver[0]}.{max_ver[1]}") # Get version support for submodule min_ver, max_ver = supported_versions_for_module(versions, "asyncio.tasks") print(f"asyncio.tasks: Python {min_ver[0]}.{min_ver[1]}+") # Output: # asyncio: 3.9 - 99.99 # asyncio.tasks: Python 3.9+ ``` -------------------------------- ### Using Incomplete Type Annotations (Python) Source: https://github.com/python/typeshed/blob/main/CONTRIBUTING.md Demonstrates how to use `_typeshed.Incomplete` for annotating fields, arguments, and return types when the full type information is not available or is partially known. This is useful for new stub files. ```python from _typeshed import Incomplete field: Incomplete # unannotated def foo(x): ... # unannotated argument and return type ``` ```python from _typeshed import Incomplete def foo(x: Incomplete | None) -> list[Incomplete]: ... ``` -------------------------------- ### Run stubtest_third_party.py Source: https://github.com/python/typeshed/blob/main/tests/README.md This script tests third-party stubs by downloading and executing arbitrary code from PyPI. It can check all third-party stubs or specific ones provided as command-line arguments. It also supports running stubtest directly with specific configurations. ```bash (.venv3)$ python3 tests/stubtest_third_party.py (.venv3)$ python3 tests/stubtest_third_party.py requests toml (.venv3)$ MYPYPATH= python3 -m mypy.stubtest \ --custom-typeshed-dir \ ``` -------------------------------- ### Modern Type Hinting Syntax with __future__ annotations in Python Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md Demonstrates the use of PEP 604 and PEP 585 syntax for type hints in Python, enabled by `from __future__ import annotations`. It highlights that while these syntaxes are supported at runtime on newer Python versions, they might require older equivalents (like `typing.Union` or `typing.Dict`) for compatibility with older Python versions when used in a runtime context, even with `__future__` annotations. ```python from __future__ import annotations from typing_extensions import assert_type x: str | int # PEP 604 syntax: okay on Python >=3.7, due to __future__ annotations assert_type(x, str | int) # Will fail at runtime on Python <3.10 (use typing.Union instead) y: dict[str, int] # PEP 585 syntax: okay on Python >= 3.7, due to __future__ annotations assert_type(y, dict[str, int]) # Will fail at runtime on Python <3.9 (use typing.Dict instead) ``` -------------------------------- ### Run All Tests for a Specific Stub Using Python Source: https://github.com/python/typeshed/blob/main/tests/README.md This script executes all defined tests for a given typeshed stub directory. It selects the oldest supported Python version if multiple are available and provides a summary of results. The argument must be a path to the stubs, e.g., 'stdlib/os' or 'stubs/requests'. ```bash (.venv3)$ python3 tests/runtests.py / ``` -------------------------------- ### Run All Linters and Formatters Locally (Bash) Source: https://github.com/python/typeshed/blob/main/CONTRIBUTING.md Executes all configured linters and formatters across all files in the project using pre-commit. This ensures local code adheres to project standards before committing. ```bash (.venv)$ pre-commit run --all-files ``` -------------------------------- ### TensorFlow Internal Class Initialization and Attributes Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Documentation for internal undocumented APIs, specifically the __init__ method for RaggedTensor and Dataset, and __getattr__ for various TensorFlow classes. These are internal details and may not be intended for direct user interaction. ```python tensorflow.RaggedTensor.__init__ tensorflow.data.Dataset.__init__ tensorflow.TensorShape.__getattr__ tensorflow.dtypes.DType.__getattr__ tensorflow.RaggedTensor.__getattr__ tensorflow.DType.__getattr__ tensorflow.Graph.__getattr__ tensorflow.Operation.__getattr__ tensorflow.Variable.__getattr__ tensorflow.keras.layers.Layer.__getattr__ tensorflow.python.feature_column.feature_column_v2.SharedEmbeddingColumnCreator.__getattr__ tensorflow.GradientTape.__getattr__ tensorflow.data.Dataset.__getattr__ tensorflow.experimental.Optional.__getattr__ tensorflow.autodiff.GradientTape.__getattr__ ``` -------------------------------- ### Run stubtest_stdlib.py Source: https://github.com/python/typeshed/blob/main/tests/README.md This script compares standard library stubs against runtime objects. Output can vary based on Python version and system specifics. It supports local allowlist files for version-specific differences and helps identify potential false positives in type checking. ```bash (.venv3)$ python3 tests/stubtest_stdlib.py ``` -------------------------------- ### Stubtest Allowlist Configuration Source: https://github.com/python/typeshed/blob/main/tests/README.md This TOML configuration snippet demonstrates how to specify mypy plugins and their configurations for stubtest. This is particularly useful for stubs that rely on mypy plugins, such as those for Django, to ensure accurate type validation. ```toml mypy_plugins = ["mypy_django_plugin.main"] mypy_plugins_config = { "django-stubs" = { "django_settings_module" = "@tests.django_settings" } } ``` -------------------------------- ### Working with Stub Paths (Python) Source: https://context7.com/python/typeshed/llms.txt Navigate the typeshed directory structure programmatically using utility functions. This Python code shows how to access standard library paths, third-party stub paths, and various test-related directories. ```python from ts_utils.paths import ( STDLIB_PATH, STUBS_PATH, distribution_path, tests_path, test_cases_path, allowlists_path ) # Core paths print(f"Standard library stubs: {STDLIB_PATH}") print(f"Third-party stubs: {STUBS_PATH}") # Third-party distribution paths requests_path = distribution_path("requests") print(f"Requests stubs: {requests_path}") # Output: stubs/requests # Test-related paths test_dir = tests_path("requests") print(f"Tests directory: {test_dir}") # Output: stubs/requests/@tests test_cases = test_cases_path("requests") print(f"Test cases: {test_cases}") # Output: stubs/requests/@tests/test_cases allowlist = allowlists_path("requests") print(f"Stubtest allowlists: {allowlist}") # Output: stubs/requests/@tests ``` -------------------------------- ### Run Standard Library Regression Tests Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md Executes the regression tests for the standard library stubs using the `regr_test.py` script. This command is run from the root of the typeshed repository and assumes the development environment is correctly set up. ```shell python tests/regr_test.py stdlib ``` -------------------------------- ### Run Mypy Tests on Typeshed Stubs with Python Source: https://github.com/python/typeshed/blob/main/tests/README.md This test runs Mypy, a static type checker, against both standard library and third-party stubs in Typeshed. It verifies that all stubs can be imported but does not check for correctness against their implementations. Configuration options are available via the --help flag. ```bash (.venv3)$ python3 tests/mypy_test.py ``` -------------------------------- ### Check Typeshed Directory Structure and Metadata with Python Source: https://github.com/python/typeshed/blob/main/tests/README.md This script validates the correctness of Typeshed's directory structure and associated metadata files. It ensures that the project adheres to the expected organization and file formats. The check is performed by running the script with Python 3. ```bash $ python3 tests/check_typeshed_structure.py ``` -------------------------------- ### Retrieve Stubtest Settings (Python) Source: https://context7.com/python/typeshed/llms.txt Fetches stubtest configuration settings for a given distribution using `ts_utils.metadata.read_stubtest_settings`. Provides information on skipping stubtest, extras, ignored missing stubs, CI platforms, and mypy plugins. ```python from ts_utils.metadata import read_stubtest_settings import sys # Get stubtest settings for a distribution settings = read_stubtest_settings("requests") print(f"Skip stubtest: {settings.skip}") print(f"Extras to install: {settings.extras}") print(f"Ignore missing stub: {settings.ignore_missing_stub}") print(f"CI platforms: {settings.ci_platforms}") print(f"Mypy plugins: {settings.mypy_plugins}") # Get system dependencies for current platform platform = sys.platform # 'linux', 'darwin', or 'win32' sys_deps = settings.system_requirements_for_platform(platform) print(f"System dependencies for {platform}: {sys_deps}") # Output: # Skip stubtest: False # Extras to install: ['socks'] # Ignore missing stub: False # CI platforms: ['linux'] # Mypy plugins: [] # System dependencies for linux: [] ``` -------------------------------- ### TensorFlow Metaclass and Runtime Access Issues Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Discusses metaclass inconsistencies for `TFRecordWriter` and `Mesh`, where the runtime metaclass is C++ based and undocumented. Also covers how `tensorflow.python.*` modules, while accessible via `from tensorflow import python`, appear missing to `stubtest` when imported directly. ```python tensorflow.io.TFRecordWriter tensorflow.experimental.dtensor.Mesh tensorflow.python.* ``` -------------------------------- ### Run typecheck_typeshed.py Source: https://github.com/python/typeshed/blob/main/tests/README.md This script acts as a wrapper for mypy, type checking the Python code within the 'scripts' and 'tests' directories of the Typeshed project. It offers various configuration options for detailed type checking. ```bash (.venv3)$ python3 tests/typecheck_typeshed.py python tests/typecheck_typeshed.py --help ``` -------------------------------- ### TensorFlow Import Magic and Re-exports Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Explains the 'cursed' import behavior in TensorFlow, where direct imports like `tensorflow.initializers` may fail while `import tensorflow as tf; tf.initializers` works. This also covers modules re-exported from `tensorflow.python` that may appear missing to stubtest. ```python # import tensorflow.initializers # import tensorflow as tf # tf.initializers tensorflow.initializers tensorflow.distribute.coordinator tensorflow.distribute.experimental.coordinator tensorflow.distribute.Strategy ``` -------------------------------- ### METADATA.toml Structure (TOML) Source: https://context7.com/python/typeshed/llms.txt Configure metadata for third-party stub packages using the METADATA.toml file. This TOML configuration defines versioning, upstream repository, dependencies, descriptions, and stubtest settings. ```toml # stubs/mypackage/METADATA.toml version = "~=1.2.3" upstream_repository = "https://github.com/example/mypackage" # Dependencies on other stub packages requires = ["types-requests>=2.0", "types-urllib3"] # Optional description shown on PyPI extra_description = "Additional information about version compatibility" # Custom stub distribution name (default: types-{package}) stub_distribution = "types-mypackage" # Mark as incomplete stub partial_stub = true # Specify minimum Python version requires_python = ">=3.10" # Mark as obsolete (package now ships types) # obsolete_since = "2.0.0" # Released on 2024-03-15 # Stubtest configuration [tool.stubtest] # Skip stubtest for this package skip = false # Install package with extras extras = ["crypto", "async"] # Ignore missing runtime objects ignore_missing_stub = false # System dependencies per platform apt_dependencies = ["libffi-dev"] brew_dependencies = ["libffi"] choco_dependencies = [] # Additional requirements for testing stubtest_requirements = ["pytest>=7.0"] # Platforms to test in CI ci_platforms = ["linux", "darwin"] # Mypy plugin support mypy_plugins = ["mypy_plugin.main"] [tool.stubtest.mypy_plugins_config] "my-plugin" = { setting = "value" } ``` -------------------------------- ### Using _typeshed types with forward references in Python Source: https://github.com/python/typeshed/blob/main/stdlib/_typeshed/README.md This code demonstrates how to enable the use of types from _typeshed (or other modules) in annotations without needing to import them directly, by using string literals (forward references). Alternatively, `from __future__ import annotations` can be used to achieve similar behavior for all annotations within the file. This is useful for breaking circular dependencies or simplifying type annotations. ```python from __future__ import annotations # Types can then be used in annotations without direct import # e.g., def func(x: '_typeshed.SomeType') -> '_typeshed.AnotherType': ... ``` -------------------------------- ### Run stubtest with Custom Configuration (Bash) Source: https://context7.com/python/typeshed/llms.txt Execute the stubtest tool with a custom configuration, specifying the MYPYPATH and a custom typeshed directory. This is useful for testing specific stub packages against a custom typeshed. ```bash MYPYPATH=stubs/requests python3 -m mypy.stubtest \ --custom-typeshed-dir . --allowlist stubs/requests/@tests/stubtest_allowlist.txt \ requests ``` -------------------------------- ### Run Third-Party Library Regression Tests Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md Executes regression tests for a specific third-party library's stubs. Replace `requests` with the name of the library for which you want to run tests. This command is run from the root of the typeshed repository. ```shell python tests/regr_test.py requests ``` -------------------------------- ### TensorFlow Tensor and SparseTensor Special Methods Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Documentation for special methods like __int__, __index__, and __getattr__ for TensorFlow's Tensor and SparseTensor classes. These methods might behave differently or be dynamically patched based on the execution environment (graph, eager, v1, v2). ```python tensorflow.Tensor.__int__ tensorflow.Tensor.numpy tensorflow.Tensor.__index__ tensorflow.sparse.SparseTensor.__getattr__ tensorflow.SparseTensor.__getattr__ ``` -------------------------------- ### Handle Inconsistent Serial.write Arguments (Python) Source: https://github.com/python/typeshed/blob/main/stubs/pyserial/@tests/stubtest_allowlist_win32.txt This snippet addresses an inconsistency error in the `serial.serialwin32.Serial.write` method's stub definition. The issue arises because the stub defines positional-only arguments based on `io.RawIOBase`, while the runtime allows normal arguments with potentially inconsistent names. This requires careful handling of method calls to ensure compatibility. ```python serial.serialwin32.Serial.write ``` -------------------------------- ### Running All Tests for a Distribution (Bash) Source: https://context7.com/python/typeshed/llms.txt Execute the complete test suite for a specific stub package, including the option to include stubtest for runtime validation. Supports testing stdlib modules and third-party stubs, with an option for specific Python versions. ```bash # Test stdlib module python3 tests/runtests.py stdlib/os # Test third-party stub python3 tests/runtests.py stubs/requests # Include stubtest (runtime validation) python3 tests/runtests.py --run-stubtest stubs/requests # Use specific Python version python3 tests/runtests.py --python-version 3.11 stdlib/asyncio ``` -------------------------------- ### TensorFlow Tensor Subscripting and Aliases Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Documentation for the __getitem__ method of TensorFlow's Tensor, which has an undocumented argument and may not preserve dynamic patching behavior. Also includes internal utility aliases. ```python tensorflow.Tensor.__getitem__ tensorflow._aliases ``` -------------------------------- ### Protobuf Generated Stubs Inconsistencies Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Addresses divergence between mypy-protobuf generated stubs (`.pyi` files) and runtime behavior for protobuf-related modules. These stubs are primarily tested within the mypy-protobuf framework and may not fully align with TensorFlow's runtime. ```python .*_pb2.* tensorflow.train.Example.* tensorflow.train.BytesList.* tensorflow.train.Feature.* tensorflow.train.FloatList.* tensorflow.train.Int64List.* tensorflow.train.ClusterDef.* tensorflow.train.ServerDef.* ``` -------------------------------- ### Import Platform-Specific Modules in Python Typeshed Source: https://github.com/python/typeshed/blob/main/stubs/pyserial/@tests/stubtest_allowlist_darwin.txt This snippet identifies modules in the Python typeshed project that are specific to the Windows operating system. These modules are not available on other platforms and are indicated by comments in the source. ```python serial.serialwin32 # Windows only serial.win32 # Windows only serial.tools.list_ports_windows # Windows only ``` -------------------------------- ### Handle Inconsistent Method Arguments in Python Typeshed Source: https://github.com/python/typeshed/blob/main/stubs/pyserial/@tests/stubtest_allowlist_darwin.txt This snippet addresses inconsistencies in method argument definitions within the Python typeshed project. Specifically, it points out the `serial.serialposix.Serial.write` method, which has positional-only arguments in stubs but normal arguments at runtime, leading to potential inconsistencies. ```python serial.serialposix.Serial.write ``` -------------------------------- ### Print Colored Output for Test Scripts Source: https://context7.com/python/typeshed/llms.txt This Python code snippet demonstrates the use of utility functions for printing colored status messages and commands within test scripts. It leverages functions like print_info, print_warning, print_error, print_success_msg, print_command, and print_divider from the ts_utils.utils module to enhance readability of script output. ```python from ts_utils.utils import ( print_info, print_warning, print_error, print_success_msg, print_command, print_divider ) # Print colored status messages print_info("Starting type checking...") print_command("mypy --strict myfile.py") print_warning("Found 3 potential issues") print_error("Type error on line 42") print_success_msg() # Prints "success" in green # Separate output sections print_divider() # Prints a row of asterisks ``` -------------------------------- ### Type Checking with Pyright (Bash) Source: https://context7.com/python/typeshed/llms.txt Validate stub files using Microsoft's pyright type checker, which requires Node.js. Supports checking all files, specific files, using stricter configurations, and checking multiple files simultaneously. ```bash # Install Node.js (required for pyright) # Check all files python3 tests/pyright_test.py # Check specific file python3 tests/pyright_test.py stdlib/sys.pyi # Use stricter configuration python3 tests/pyright_test.py -p pyrightconfig.stricter.json # Check multiple files python3 tests/pyright_test.py stdlib/os.pyi stdlib/pathlib.pyi ``` -------------------------------- ### Check Typeshed Repository Structure with Python Source: https://context7.com/python/typeshed/llms.txt This script validates the METADATA.toml files and directory structure of the typeshed repository. It checks for well-formed metadata, valid version specifiers, existing dependencies, adherence to directory conventions, and absence of unknown fields. It is executed using the python3 interpreter. ```bash # Verify all metadata files and directory structure python3 tests/check_typeshed_structure.py # This validates: # - All METADATA.toml files are well-formed # - Version specifiers are valid # - Dependencies exist # - Directory structure follows conventions # - No unknown fields in metadata ``` -------------------------------- ### Importing _typeshed types in Python implementation files Source: https://github.com/python/typeshed/blob/main/stdlib/_typeshed/README.md This snippet shows how to import types from the _typeshed package into Python implementation (.py) files. It utilizes the TYPE_CHECKING constant from the typing module to ensure these imports are only active during type checking and do not affect runtime behavior. No external dependencies are required beyond the standard 'typing' module. ```python from typing import TYPE_CHECKING if TYPE_CHECKING: from _typeshed import ... ``` -------------------------------- ### TensorFlow Layer Call Method Stubbing Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Discusses the `call` method in TensorFlow Keras layers and regularizers. Stubs may not accurately reflect runtime behavior due to keyword argument handling in subclasses and optional `training`/`mask` arguments, leading to potential false positives in type checking. ```python tensorflow.keras.layers.*.call tensorflow.keras.regularizers.Regularizer.__call__ tensorflow.keras.constraints.Constraint.__call__ ``` -------------------------------- ### TensorFlow Layer and Model __new__ Magic Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Highlights the `__new__` method in TensorFlow Keras Layer and Model classes. This method performs significant magic, returning different internal types based on the TensorFlow execution mode, which is considered an implementation detail. ```python tensorflow.keras.layers.Layer.__new__ ``` -------------------------------- ### Identify Private Aliases in Python Typeshed Source: https://github.com/python/typeshed/blob/main/stubs/pyserial/@tests/stubtest_allowlist_darwin.txt This snippet highlights intended private aliases within the Python typeshed project. These aliases are used for internal purposes and are marked with comments indicating their private nature. ```python serial.tools.list_ports_posix.plat serial.serialposix.plat ``` -------------------------------- ### Testing Type Inferences with `assert_type` Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md Demonstrates the usage of `typing.assert_type` within test cases to programmatically check if a type checker's inferred type for a given expression matches the expected type. ```python from typing import assert_type my_variable: int = 5 assert_type(my_variable, int) ``` -------------------------------- ### TensorFlow Layer build and compute_output_shape Stubbing Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Explains why `build` and `compute_output_shape` methods in TensorFlow Keras layers are marked as positional-only in stubs. Argument names are inconsistent across layers, and documentation does not mention these disagreements, suggesting they are implementation details. ```python tensorflow.keras.layers.*.build tensorflow.keras.layers.*.compute_output_shape ``` -------------------------------- ### Type Checking with Mypy (Bash) Source: https://context7.com/python/typeshed/llms.txt Verify that stub files can be imported without errors using the mypy type checker. Supports checking all stubs, specific Python versions, only the standard library, or specific stub packages. ```bash # Check all stubs with mypy python3 tests/mypy_test.py # Check with specific Python version python3 tests/mypy_test.py --python-version 3.11 # Check only standard library python3 tests/mypy_test.py --stdlib-only # Check specific stub package python3 tests/mypy_test.py --filter requests ``` -------------------------------- ### Parse Dependencies for Stub Packages (Python) Source: https://context7.com/python/typeshed/llms.txt Determines typeshed-internal and external dependencies for a stub package using `ts_utils.metadata.read_dependencies` and `get_recursive_requirements`. Resolves direct and transitive dependencies. ```python from ts_utils.metadata import read_dependencies, get_recursive_requirements # Get direct dependencies deps = read_dependencies("requests") print(f"Typeshed dependencies: {deps.typeshed_pkgs}") print(f"External dependencies: {deps.external_pkgs}") # Output: # Typeshed dependencies: (Requirement('urllib3>=2'),) # External dependencies: () # Get recursive dependencies (including transitive) recursive_deps = get_recursive_requirements("caldav") print(f"All typeshed deps: {recursive_deps.typeshed_pkgs}") print(f"All external deps: {recursive_deps.external_pkgs}") # This resolves the full dependency tree: # caldav -> requests -> urllib3 ``` -------------------------------- ### Platform-Specific Module Imports in Python Serial Stubs Source: https://github.com/python/typeshed/blob/main/stubs/pyserial/@tests/stubtest_allowlist_linux.txt These are import errors indicating that certain modules within the 'serial' library are intended for specific operating systems. Importing them on unsupported platforms will result in an error. Ensure your code checks the platform or avoids direct imports of these modules. ```python serial.serialwin32 # Windows only serial.win32 # Windows only serial.tools.list_ports_osx # Mac only serial.tools.list_ports_windows # Windows only ``` -------------------------------- ### Suppressing Expected Errors with `# type: ignore` Source: https://github.com/python/typeshed/blob/main/tests/REGRESSION.md Illustrates the use of `# type: ignore` comments in conjunction with specific type checker settings (`--warn-unused-ignores` for mypy, `reportUnnecessaryTypeIgnoreComment` for pyright) to test scenarios where an error is expected. ```python # This line is expected to produce a type error result = "hello" + 5 # type: ignore ``` -------------------------------- ### TensorFlow Tensor Methods Removed in 2.14 Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Details on TensorFlow Tensor methods like consumers, graph, and op that were removed in version 2.14 but are still defined for internal subclasses used at runtime. This indicates a difference between public API stubs and internal implementation. ```python tensorflow.Tensor.consumers tensorflow.Tensor.graph tensorflow.Tensor.op ``` -------------------------------- ### TensorFlow IO Feature NamedTuple Mismatches Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Details discrepancies in the `__new__` method's first argument name between runtime's `namedtuple` and stubs' `NamedTuple` for TensorFlow IO feature classes. This difference arises from how these types are handled internally. ```python tensorflow.io.RaggedFeature.__new__ tensorflow.io.FixedLenSequenceFeature.__new__ tensorflow.io.FixedLenFeature.__new__ tensorflow.io.SparseFeature.__new__ ``` -------------------------------- ### Read Metadata for Third-Party Type Stubs (Python) Source: https://context7.com/python/typeshed/llms.txt Parses and extracts metadata from METADATA.toml files for third-party stubs using `ts_utils.metadata.read_metadata`. Handles potential `NoSuchStubError` if the stub is not found. ```python from ts_utils.metadata import read_metadata, NoSuchStubError try: # Read metadata for requests stubs metadata = read_metadata("requests") print(f"Distribution: {metadata.distribution}") print(f"Stub package name: {metadata.stub_distribution}") print(f"Version spec: {metadata.version_spec}") print(f"Requires: {metadata.requires}") print(f"Upstream repo: {metadata.upstream_repository}") print(f"Is obsolete: {metadata.is_obsolete}") print(f"Uploaded to PyPI: {metadata.uploaded_to_pypi}") print(f"Python versions: {metadata.requires_python}") # Output example: # Distribution: requests # Stub package name: types-requests # Version spec: ~=2.32.4 # Requires: [Requirement('urllib3>=2')] # Upstream repo: https://github.com/psf/requests # Is obsolete: False # Uploaded to PyPI: True # Python versions: >=3.9 except NoSuchStubError as e: print(f"Error: {e}") ``` -------------------------------- ### Define Platform-Variant Type ULONG_PTR (Python) Source: https://github.com/python/typeshed/blob/main/stubs/pyserial/@tests/stubtest_allowlist_win32.txt This snippet points to a type definition inconsistency for `serial.win32.ULONG_PTR`. The type of `ULONG_PTR` can vary between `c_longlong` and `c_ulong` depending on the Windows variant. This difference can cause issues during stub testing (`stubtest`) where only one definition is observed, leading to potential type mismatches. ```python serial.win32.ULONG_PTR ``` -------------------------------- ### TensorFlow NN Sigmoid Cross Entropy Default Values Source: https://github.com/python/typeshed/blob/main/stubs/tensorflow/@tests/stubtest_allowlist.txt Notes that the `sigmoid_cross_entropy_with_logits` function in `tensorflow.nn` has default values set to `None`, which are not valid according to the function's actual requirements, potentially causing issues. ```python tensorflow.nn.sigmoid_cross_entropy_with_logits ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.