### Install Typeguard Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Install the typeguard library using pip. This is the first step before using any of its features. ```bash pip install typeguard ``` -------------------------------- ### Enabling and Observing Typeguard Debug Output Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/instrumentation.md This example demonstrates how to enable debug instrumentation globally and install an import hook for a specific package. It then imports a module and shows the expected format of the instrumented source code output to stderr when debugging is active. ```python global_config.debug_instrumentation = True hook = install_import_hook(["myapp"]) import myapp.module # Output to stderr: # Source code of '/path/to/myapp/module.py' after instrumentation: # def func(x: int) -> str: # __typeguard_memo = TypeCheckMemo(globals(), locals()) # check_type_internal(x, int, __typeguard_memo) # ... ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/agronholm/typeguard/blob/master/docs/contributing.md Install pre-commit hooks to ensure code style and quality checks are performed locally before committing. This helps maintain consistency with checks performed on GitHub. ```bash pre-commit install ``` -------------------------------- ### Install Import Hook Function Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Installs the import hook for specified packages, allowing for custom module loading behavior. ```python def install_import_hook( packages: Iterable[str] | None = None, *, cls: type[TypeguardFinder] = TypeguardFinder, ) -> ImportHookManager ``` -------------------------------- ### Set Up Development Environment with Pytest Source: https://github.com/agronholm/typeguard/blob/master/docs/contributing.md Set up a virtual environment, install the project in development mode with test dependencies, and prepare to run Pytest directly. ```bash python -m venv venv source venv/bin/activate pip install -e .[test] ``` -------------------------------- ### Complete Plugin Example: CustomType and Checker Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/plugin-system.md This snippet shows a complete example of a custom type 'CustomType', its checker function 'check_custom_type', and a lookup function 'custom_type_lookup'. It demonstrates how to define custom types and the logic for checking them, including optional checks based on type arguments. ```python # mymodule.py - Custom type checker plugin from typing import Any, Tuple, get_origin, get_args from typeguard._checkers import TypeCheckerCallable, TypeCheckLookupCallback from typeguard._exceptions import TypeCheckError from typeguard._memo import TypeCheckMemo class CustomType: """A custom type we want to add checking for.""" def __init__(self, value: int): if not isinstance(value, int): raise ValueError("value must be int") self.value = value def check_custom_type( value: Any, origin_type: Any, args: Tuple[Any, ...], memo: TypeCheckMemo, ) -> None: """Checker for CustomType.""" if not isinstance(value, CustomType): raise TypeCheckError(f"expected CustomType instance, got {type(value).__name__}") # Optionally check the value parameter if type args are provided if args: expected_value_type = args[0] # If CustomType[int] was used from typeguard._checkers import check_type_internal check_type_internal(value.value, expected_value_type, memo) def custom_type_lookup( origin_type: Any, args: Tuple[Any, ...], extras: Tuple[Any, ...], ) -> TypeCheckerCallable | None: """Lookup function for custom types.""" if origin_type is CustomType: return check_custom_type return None # For entry point registration: # In pyproject.toml: # [project.entry-points."typeguard.checker_lookup_functions"] # custom = "mymodule:custom_type_lookup" ``` -------------------------------- ### Access Global Config Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Example of how to access and modify the global configuration for Typeguard. ```APIDOC ## Access Global Config ### Description Demonstrates how to access and modify the global configuration settings for Typeguard. ### Example ```python import typeguard from typeguard.importhook import ForwardRefPolicy # Set the forward reference policy to raise errors typeguard.config.forward_ref_policy = ForwardRefPolicy.ERROR ``` ``` -------------------------------- ### Example Usage of TypeHintWarning Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/errors.md Shows how TypeHintWarning is emitted when a forward reference cannot be resolved. This example uses ForwardRefPolicy.WARN and attempts to resolve an unresolvable type. ```python import warnings from typeguard import check_type, ForwardRefPolicy warnings.simplefilter("always") # This will emit TypeHintWarning if "NonexistentType" can't be resolved from typing import ForwardRef unresolvable = ForwardRef("NonexistentType") check_type(some_value, unresolvable, forward_ref_policy=ForwardRefPolicy.WARN) # Output: TypeHintWarning: Cannot resolve forward reference 'NonexistentType' ``` -------------------------------- ### Example Usage of TypeCheckWarning Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/errors.md Demonstrates how to catch TypeCheckWarning when type checking fails and is configured to warn. This example sets a warning filter to 'error' for TypeCheckWarning to ensure it's caught. ```python import warnings from typeguard import check_type, warn_on_error warnings.filterwarnings("error", category=TypeCheckWarning) try: check_type("string", int, typecheck_fail_callback=warn_on_error) except TypeCheckWarning as w: print(f"Type warning: {w}") ``` -------------------------------- ### Run Tox Test Suite Source: https://github.com/agronholm/typeguard/blob/master/docs/contributing.md Execute the test suite using Tox against all supported Python versions. Tox manages dependency installation in isolated virtual environments. ```bash tox ``` -------------------------------- ### CollectionCheckStrategy Example: Checking First Item vs. All Items Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/types.md Demonstrates the difference between checking only the first item and checking all items in a collection using CollectionCheckStrategy. FIRST_ITEM is the default behavior. ```python from typeguard import check_type, CollectionCheckStrategy # Only checks first item (default) check_type([1, 2, "three"], list[int], collection_check_strategy=CollectionCheckStrategy.FIRST_ITEM) # Succeeds: first item is int # Checks all items check_type([1, 2, "three"], list[int], collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS) # Raises TypeCheckError: "three" is not int ``` -------------------------------- ### Registering a Custom Type Checker via Entry Point Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/plugin-system.md This example shows how to define a custom type checker lookup function and register it using a project's entry points. This is useful for making custom checkers discoverable by TypeGuard. ```python # In a setup.py or pyproject.toml [project.entry-points."typeguard.checker_lookup_functions"] my_checker = "mymodule:my_checker_lookup" # In mymodule.py from typeguard._checkers import TypeCheckLookupCallback, TypeCheckerCallable def my_checker_lookup( origin_type: Any, args: tuple[Any, ...], extras: tuple[Any, ...] ) -> TypeCheckerCallable | None: if origin_type is MyCustomType: return my_custom_checker return None def my_custom_checker(value: Any, origin_type: Any, args: tuple[Any, ...], memo: TypeCheckMemo) -> None: # Type checking logic pass ``` -------------------------------- ### TypeCheckError Usage Example Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/errors.md Demonstrates how to catch and print `TypeCheckError` exceptions, showing how path elements are included in the error message. ```python from typeguard import TypeCheckError, check_type try: check_type({"age": "not an int"}, dict[str, int]) except TypeCheckError as e: print(str(e)) # Output: 'of key "age" expected int, got str' # Catching at function level try: result = check_return_type("string") # In function with -> int except TypeCheckError as e: # Path shows "the return value" context print(str(e)) ``` -------------------------------- ### install_import_hook Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Installs a module import hook to enable type checking for specified packages. ```APIDOC ## Function: install_import_hook ### Description Installs a module import hook to enable type checking for specified packages. ### Signature `install_import_hook(packages)` ### Parameters - **packages**: A list or tuple of package names to hook into. ``` -------------------------------- ### Catching InstrumentationWarning Example Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/errors.md Demonstrates how to set up warnings to be treated as errors and how to catch an InstrumentationWarning that may occur when decorating a function with @typechecked. This is useful for debugging instrumentation issues. ```python import warnings from typeguard import InstrumentationWarning, typechecked warnings.filterwarnings("error", category=InstrumentationWarning) try: # This may fail on certain functions (e.g., REPL-defined, wrapped, etc.) @typechecked def my_function(x: int) -> int: return x except InstrumentationWarning as w: print(f"Instrumentation failed: {w}") # Pytest-related # pytest --typeguard-packages=myapp,already_imported_lib # Will warn about already_imported_lib being already loaded ``` -------------------------------- ### install_import_hook Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/api-reference-decorators.md Installs a Python import hook that automatically instruments modules for type checking as they are imported. It returns a context manager for managing the hook. ```APIDOC ## install_import_hook ### Description Install a Python import hook that automatically instruments modules for type checking as they are imported. ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | packages | Iterable[str] | None | Package names to instrument; None instruments all packages | | cls | type[TypeguardFinder] | TypeguardFinder | Custom meta path finder class for advanced use cases | ### Return Type **ImportHookManager**: A context manager and handle for uninstalling the hook. ### Methods on ImportHookManager - **uninstall()**: Immediately uninstall the hook from `sys.meta_path` ### Context Manager Support The returned manager can be used as a context manager to automatically uninstall the hook on exit. ### Notes - Only affects modules loaded **after** the hook is installed - Already-imported modules are not retroactively instrumented - May clash with other import hooks - Emits `InstrumentationWarning` for packages already imported ### Example ```python from typeguard import install_import_hook # Instrument specific packages hook = install_import_hook(["myapp", "mylib"]) # Now import and use instrumented modules import myapp # All code in myapp will have type checks # Later, uninstall the hook hook.uninstall() # Or use as context manager with install_import_hook(["myapp"]): import myapp.utils # Type checks active # Hook is automatically uninstalled here # Instrument all packages hook = install_import_hook() # None means all modules import anything # Will be instrumented hook.uninstall() ``` ``` -------------------------------- ### Install and Use Import Hook for Automatic Type Checking Source: https://github.com/agronholm/typeguard/blob/master/docs/userguide.md Install the import hook before importing modules to automatically instrument type-annotated functions. This method modifies the AST upon module loading without altering disk files. ```python from typeguard import install_import_hook install_import_hook('myapp') from myapp import some_module # import only AFTER installing the hook, or it won't take effect ``` -------------------------------- ### install_import_hook() Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Installs the import hook for typeguard, allowing for instrumentation of specified packages during module imports. It returns an ImportHookManager to control the hook's lifecycle. ```APIDOC ## install_import_hook() ### Description Install the import hook. ### Parameters - **packages** (Iterable[str] | None) - Optional. A list of packages to instrument. - **cls** (type[TypeguardFinder]) - Optional. The TypeguardFinder class to use. Defaults to TypeguardFinder. ### Returns - **ImportHookManager** - A handle for managing the import hook. ``` -------------------------------- ### Install Python import hook for automatic type checking Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/api-reference-decorators.md Install a Python import hook to automatically instrument modules for type checking as they are imported. This hook only affects modules loaded after it is installed and does not retroactively instrument already-imported modules. It may clash with other import hooks and emits InstrumentationWarning for packages already imported. The hook can be uninstalled manually or used as a context manager. ```python from typeguard import install_import_hook # Instrument specific packages hook = install_import_hook(["myapp", "mylib"]) # Now import and use instrumented modules import myapp # All code in myapp will have type checks # Later, uninstall the hook hook.uninstall() # Or use as context manager with install_import_hook(["myapp"]): import myapp.utils # Type checks active # Hook is automatically uninstalled here # Instrument all packages hook = install_import_hook() # None means all modules import anything # Will be instrumented hook.uninstall() ``` -------------------------------- ### Implement TypeCheckFailCallback Functions Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/types.md Provides example implementations for TypeCheckFailCallback. The `log_and_ignore` function logs errors, while `strict_callback` re-raises them with additional context. Both require importing TypeCheckError and TypeCheckMemo. ```python from typeguard import TypeCheckError, TypeCheckMemo def log_and_ignore(exc: TypeCheckError, memo: TypeCheckMemo) -> None: """Log type errors instead of raising them.""" logger.error(f"Type check failed: {exc}") def strict_callback(exc: TypeCheckError, memo: TypeCheckMemo) -> None: """Re-raise with additional context.""" raise RuntimeError(f"Type safety violation: {exc}") from exc ``` -------------------------------- ### TypeCheckError Example Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Demonstrates a TypeCheckError raised when a value does not match the expected type. Use `check_type()` with the correct value and type to resolve. ```python check_type(5, str) # Error: is not an instance of str ``` -------------------------------- ### Selective Instrumentation with Import Hook Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/instrumentation.md Install an import hook to selectively instrument specific packages or modules. This allows you to control which parts of your application have type checking enabled. ```python # Option 2: Selective instrumentation hook = install_import_hook(["myapp.slow"]) # Only instrument this package ``` -------------------------------- ### Python check_type Usage Examples Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/api-reference-functions.md Demonstrates various ways to use the `check_type` function, including basic type checking, using optional parameters like `collection_check_strategy`, type-safe casting, and providing a custom error handler. ```python from typeguard import check_type # Basic type checking value = check_type([1, 2, 3], list[int]) # With optional parameters check_type( {"name": "Alice", "age": 30}, dict[str, str | int], collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS, ) # Type-safe casting my_int: int = check_type(user_input, int) # Raises if not int # With custom error handler def log_error(exc: TypeCheckError, memo: TypeCheckMemo) -> None: logger.warning(f"Type check failed: {exc}") check_type(value, str, typecheck_fail_callback=log_error) ``` -------------------------------- ### Annotated Assignment (AnnAssign) Example Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/instrumentation.md Demonstrates an annotated assignment node in Python. The transformer modifies this to use `check_variable_assignment()` for type checking. ```python count: int = 5 # AnnAssign node # Transformed to use check_variable_assignment() ``` -------------------------------- ### Forward Reference Error Example Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Illustrates a 'Cannot resolve forward reference' error when a type hint refers to an undefined class. Ensure the class is defined or configure `ForwardRefPolicy.IGNORE`. ```python check_type(obj, "UndefinedClass") ``` -------------------------------- ### Customize Import Hook with a Custom Finder Source: https://github.com/agronholm/typeguard/blob/master/docs/userguide.md Customize the import hook's module selection logic by providing a custom `TypeguardFinder` subclass. This example instruments all loaded modules regardless of their names. ```python from typeguard import TypeguardFinder, install_import_hook class CustomFinder(TypeguardFinder): def should_instrument(self, module_name: str): # disregard the module names list and instrument all loaded modules return True install_import_hook('', cls=CustomFinder) ``` -------------------------------- ### Configure Pytest for Typeguard Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Configures the typeguard plugin for pytest. This function installs an import hook based on the provided configuration, enabling type checking during test runs. ```python def pytest_configure(config: Config) -> None: pass ``` -------------------------------- ### Python Typeguard Error Path Context Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/errors.md This example demonstrates how typeguard builds a detailed error path for nested dictionaries, showing the exact location and type mismatch. It's useful for debugging complex data structures. ```python from typeguard import check_type, TypeCheckError # Example showing how error paths build context def validate_config(config: dict[str, dict[str, int]]) -> None: try: check_type(config, dict[str, dict[str, int]]) except TypeCheckError as e: print(e) # Example output: 'of key "database" of key "port" expected int, got str' # Multi-level nesting shows complete context trail data = { "database": { "port": "5432" # Should be int } } validate_config(data) # Raises: of key "database" of key "port" expected int, got str ``` -------------------------------- ### Typechecked Function with Potential Instrumentation Warnings Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/instrumentation.md This example shows a function decorated with @typechecked. It may emit InstrumentationWarning under specific conditions such as the function having no associated code, missing '__module__' attribute, being defined in a REPL, or being wrapped with unsupported decorators. ```python from typeguard import typechecked @typechecked def func(): pass # May emit InstrumentationWarning if: # - "no code associated" # - "__module__ attribute is not set" # - "cannot instrument functions defined in a REPL" # - Wrapped with unsupported decorators # - Instrumentor cannot find the target function # - Target function not found in AST ``` -------------------------------- ### Already Imported Error Example Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Addresses the 'already imported' error when the Typeguard hook is not installed before modules are imported. Install the hook prior to module imports using `pytest --typeguard-packages`. ```bash pytest --typeguard-packages=already_loaded_module ``` -------------------------------- ### Build Documentation with Tox Source: https://github.com/agronholm/typeguard/blob/master/docs/contributing.md Build the project documentation using Tox with the 'docs' environment. The output will be placed in 'build/sphinx/html'. ```bash tox -e docs ``` -------------------------------- ### Access Global Configuration Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Demonstrates how to import the typeguard library and modify global configuration settings, such as the forward reference policy. ```python import typeguard typeguard.config.forward_ref_policy = ForwardRefPolicy.ERROR ``` -------------------------------- ### Typeguard Package Structure Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Illustrates the directory and file layout of the typeguard package, showing the location of core modules and utility files. ```text typeguard/ ├── __init__.py # Main package entry point ├── _functions.py # Core check_type and argument checking functions ├── _decorators.py # @typechecked decorator and instrumentation ├── _checkers.py # Type checker functions and lookup system ├── _config.py # Configuration classes ├── _exceptions.py # Exception and warning classes ├── _importhook.py # Import hook for module instrumentation ├── _memo.py # TypeCheckMemo class ├── _suppression.py # suppress_type_checks context manager ├── _transformer.py # AST transformer for code instrumentation ├── _utils.py # Utility functions └── _pytest_plugin.py # Pytest integration plugin ``` -------------------------------- ### Compare Collection Check Strategies Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/type-checking-guide.md Compares the performance of `CollectionCheckStrategy.FIRST_ITEM` versus `CollectionCheckStrategy.ALL_ITEMS` for large collections. `FIRST_ITEM` is significantly faster. ```python from typeguard import check_type, CollectionCheckStrategy import time large_list = list(range(100000)) # Fast: checks only first item start = time.time() check_type( large_list, list[int], collection_check_strategy=CollectionCheckStrategy.FIRST_ITEM, ) print(f"FIRST_ITEM: {time.time() - start:.6f}s") # ~0.00001s # Slow: checks all items start = time.time() check_type( large_list, list[int], collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS, ) print(f"ALL_ITEMS: {time.time() - start:.6f}s") # ~0.01s+ ``` -------------------------------- ### Get Function Name Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Retrieves the qualified name of a function. This is a specialized version of `qualified_name` specifically for callable objects. ```python def function_name(func: Callable[..., Any]) -> str ``` -------------------------------- ### Access and Modify Global Configuration Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/configuration.md Demonstrates how to read and change global TypeGuard configuration settings like forward reference policy and collection check strategy using the typeguard module. ```python import typeguard # Read current settings print(typeguard.config.forward_ref_policy) print(typeguard.config.collection_check_strategy) # Modify settings typeguard.config.forward_ref_policy = typeguard.ForwardRefPolicy.IGNORE typeguard.config.typecheck_fail_callback = typeguard.warn_on_error ``` -------------------------------- ### Create Feature Branch Source: https://github.com/agronholm/typeguard/blob/master/docs/contributing.md Create a new branch for your feature or fix. Replace 'myfixname' with a descriptive name for your changes. ```bash git checkout -b myfixname ``` -------------------------------- ### Type-Safe Configuration Loading Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Load configuration data from a JSON file and validate its structure against a specified type hint using `check_type`. This ensures configuration values conform to expected types. ```python from typeguard import check_type import json def load_config(path: str) -> dict[str, int]: with open(path) as f: data = json.load(f) return check_type(data, dict[str, int]) ``` -------------------------------- ### Typeguard Configuration Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Details on configuration enums, dataclasses, and global configuration instances. ```APIDOC ## Module: typeguard._config Configuration classes and global state. ### Classes #### ForwardRefPolicy Enum for forward reference handling: ```python class ForwardRefPolicy(Enum): ERROR = auto() WARN = auto() IGNORE = auto() ``` #### CollectionCheckStrategy Enum for collection checking: ```python class CollectionCheckStrategy(Enum): FIRST_ITEM = auto() ALL_ITEMS = auto() def iterate_samples(self, collection: Iterable[T]) -> Iterable[T] ``` #### TypeCheckConfiguration Dataclass for configuration: ```python @dataclass class TypeCheckConfiguration: forward_ref_policy: ForwardRefPolicy = ForwardRefPolicy.WARN typecheck_fail_callback: TypeCheckFailCallback | None = None collection_check_strategy: CollectionCheckStrategy = CollectionCheckStrategy.FIRST_ITEM debug_instrumentation: bool = False ``` ### Module-Level Variables #### global_config Global TypeCheckConfiguration instance: ```python global_config = TypeCheckConfiguration() ``` **Source**: `typeguard/_config.py` ``` -------------------------------- ### Configuration Validation with TypedDict Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/type-checking-guide.md Loads and validates application configuration from a JSON file against a TypedDict schema. Ensures configuration adheres to expected types and literal values. ```python from typing import Literal, TypedDict from typeguard import check_type, TypeCheckError import json class AppConfig(TypedDict): environment: Literal["dev", "staging", "production"] debug: bool log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] def load_config(config_file: str) -> AppConfig: with open(config_file) as f: data = json.load(f) return check_type(data, AppConfig) # Type-safe config loading config = load_config("config.json") ``` -------------------------------- ### load_plugins Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Loads available checker plugins for Typeguard. ```APIDOC ## Function: load_plugins ### Description Loads available checker plugins for Typeguard. ### Signature `load_plugins()` ``` -------------------------------- ### Registering TypeGuard Plugins via Entry Points Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/README.md Define TypeGuard checker lookup functions as entry points in your project's `pyproject.toml` file. This allows TypeGuard to discover and use custom checker implementations. ```toml [project.entry-points."typeguard.checker_lookup_functions"] my_plugin = "mymodule:my_checker_lookup" ``` -------------------------------- ### Configure TypeGuard in pyproject.toml Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/configuration.md Shows how to configure TypeGuard options within the [tool.pytest.ini_options] section of a pyproject.toml file, including package instrumentation and policy settings. ```toml [tool.pytest.ini_options] # Configure typeguard options via pytest ini options typeguard-packages = ["myapp", "mylib"] typeguard-forward-ref-policy = "WARN" typeguard-collection-check-strategy = "FIRST_ITEM" typeguard-debug-instrumentation = false ``` -------------------------------- ### Get Type Name Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Retrieves a human-readable display name for a given type. This utility is helpful for generating informative error messages or logging information related to types. ```python def get_type_name(type_: Any) -> str ``` -------------------------------- ### Configure TypeGuard in pytest.ini Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/configuration.md Demonstrates how to configure TypeGuard options directly in a pytest.ini file, similar to pyproject.toml, for package instrumentation and policy settings. ```ini [pytest] typeguard-packages = myapp,mylib typeguard-forward-ref-policy = WARN typeguard-collection-check-strategy = FIRST_ITEM typeguard-debug-instrumentation = false ``` -------------------------------- ### Get Qualified Name Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Obtains the fully qualified name of an object, including its module path. An optional argument can prepend the class name if the object is a method or attribute within a class. ```python def qualified_name(obj: Any, *, add_class_prefix: bool = False) -> str ``` -------------------------------- ### Instrumentation Error Example Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Shows an 'instrumentor did not find the target function' error when using the `@typechecked` decorator on a function without accessible source code. Ensure the function's source is available. ```python @typechecked def func(): pass ``` -------------------------------- ### Register Type Checker via Project Entry Point Source: https://github.com/agronholm/typeguard/blob/master/docs/extending.md Configure your project's `pyproject.toml` to register a custom type checker lookup function using entry points. This method is recommended for packaged libraries and requires reinstallation for the entry point to be discoverable. ```toml [project.entry-points] typeguard.checker_lookup = {myplugin = "myapp.my_plugin_module:my_checker_lookup"} ``` -------------------------------- ### Load Plugins Function Signature Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Loads checker plugins from entry points, extending the type checking capabilities. ```python def load_plugins() -> None ``` -------------------------------- ### Check Function Argument Types Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/api-reference-functions.md Use check_argument_types() at the start of a function to verify that all argument values match their annotated types. This function inspects the calling frame to retrieve the signature and local variables. ```python from typeguard import check_argument_types def process_user(name: str, age: int, emails: list[str]) -> None: check_argument_types() # Verify all arguments match their annotations # ... rest of function implementation ``` -------------------------------- ### Closure Handling with Typechecked Decorator Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/instrumentation.md Illustrates how the `typechecked` decorator handles closure variables. The example shows an `outer` function defining an `inner` function, where the closure variable 'x' is preserved and type-checked during instrumentation. ```python @typechecked def outer(x: int): def inner(y: int) -> int: return x + y return inner # Closure variable 'x' is preserved and type-checked at instrumentation time ``` -------------------------------- ### Add Type Checking to Existing Code with Typeguard Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/README.md Use `install_import_hook` at application startup to instrument all imported modules within specified packages for type checking. ```python from typeguard import install_import_hook # At application startup hook = install_import_hook(["myapp"]) # All imported modules are now instrumented import myapp ``` -------------------------------- ### Access Global Configuration via Module __getattr__ Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/configuration.md Shows how to access the global configuration object using module-level __getattr__, allowing direct modification of settings like collection check strategy. ```python from typeguard import config # This triggers __getattr__ and returns the global_config object config.collection_check_strategy = CollectionCheckStrategy.ALL_ITEMS ``` -------------------------------- ### Distinguishing Decorator Arguments Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/api-reference-classes.md Illustrates the difference between using default decorator arguments (which implicitly use unset) and explicitly providing unset. ```python from typeguard import typechecked, unset # These are different: @typechecked() # Uses unset for all parameters def func1(): pass @typechecked(forward_ref_policy=unset) # Explicitly uses unset def func2(): pass ``` -------------------------------- ### Get Stack Level for Warnings Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Determines the appropriate stack level to use when issuing warnings. This helps ensure that warnings point to the correct line of code in the user's application rather than internal library code. ```python def get_stacklevel() -> int ``` -------------------------------- ### Public API Classes Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Core classes for exceptions, configuration, and type checking context. ```APIDOC ## Classes ### `TypeCheckError` #### Description Exception for type mismatches. ### `TypeCheckWarning` #### Description Warning for type mismatches. ### `TypeCheckConfiguration` #### Description Configuration dataclass. ### `TypeCheckMemo` #### Description Type check context. ### `ImportHookManager` #### Description Import hook handle. ### `TypeguardFinder` #### Description Import hook finder. ### `ForwardRefPolicy` #### Description Enum for forward reference handling. ### `CollectionCheckStrategy` #### Description Enum for collection checking strategy. ### `InstrumentationWarning` #### Description Warning for instrumentation issues. ### `TypeHintWarning` #### Description Warning for unresolvable type hints. ``` -------------------------------- ### Run Pytest Directly Source: https://github.com/agronholm/typeguard/blob/master/docs/contributing.md Execute the test suite directly using Pytest after setting up the development environment. ```bash pytest ``` -------------------------------- ### Type Checking with Default Error Raising Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/README.md Demonstrates how to use check_type and catch potential TypeCheckError exceptions. ```python from typeguard import check_type, TypeCheckError try: check_type(value, int) except TypeCheckError as e: # Handle error pass ``` -------------------------------- ### Check Type with ALL_ITEMS Strategy Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Employ the ALL_ITEMS strategy for thorough collection checking, which verifies every item but is slower. ```python # Checks all items - slower but thorough check_type( [1, 2, "three"], list[int], collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS, ) # Raises TypeCheckError: "three" is not int ``` -------------------------------- ### Configure Pytest Plugin Options Source: https://github.com/agronholm/typeguard/blob/master/docs/userguide.md Configure Typeguard pytest plugin options using `pyproject.toml`. This allows for detailed customization of package instrumentation, debugging, failure callbacks, forward reference policies, and collection strategies. ```toml [tool.pytest.ini_options] typeguard-packages = """ foo.bar xyz""" typeguard-debug-instrumentation = true typeguard-typecheck-fail-callback = "mypackage:failcallback" typeguard-forward-ref-policy = "ERROR" typeguard-collection-check-strategy = "ALL_ITEMS" ``` -------------------------------- ### TypeguardLoader Source to Code Transformation Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/instrumentation.md This snippet shows the core logic of the TypeguardLoader class, demonstrating how it takes source data, parses it into an AST, transforms the AST using TypeguardTransformer, and compiles it into executable bytecode. It's used for intercepting and instrumenting module loading. ```python class TypeguardLoader(SourceFileLoader): @staticmethod def source_to_code( data: Buffer | str | ast.Module | ast.Expression | ast.Interactive, path: Buffer | str | PathLike[str] = "", fullname: str | None = None, *, _optimize: int = -1, ) -> CodeType: # Parse source to AST module = ast.parse(source, filename, "exec") # Transform AST tree = TypeguardTransformer().visit(module) ast.fix_missing_locations(tree) # Compile to bytecode return compile(tree, filename, "exec", ...) ``` -------------------------------- ### TypeGuard Module Structure Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/README.md Overview of the key modules within the TypeGuard library and their primary responsibilities. ```text typeguard/ ├── _functions.py # check_type, check_argument_types, check_return_type ├── _decorators.py # @typechecked, instrument() ├── _checkers.py # Type checker implementations ├── _config.py # Configuration classes ├── _exceptions.py # Exception types ├── _importhook.py # Import hook and module loading ├── _memo.py # TypeCheckMemo class ├── _suppression.py # suppress_type_checks() ├── _transformer.py # AST transformation ├── _utils.py # Utility functions └── _pytest_plugin.py # Pytest integration ``` -------------------------------- ### Clone Forked Repository Source: https://github.com/agronholm/typeguard/blob/master/docs/contributing.md Clone your forked repository to your local machine using Git. Replace 'yourusername' with your actual GitHub username. ```bash git clone git@github.com/yourusername/typeguard ``` -------------------------------- ### Register Custom Checker via Entry Point Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Register a custom type checker using a project's entry points in pyproject.toml. This is an alternative method for plugin registration. ```toml # pyproject.toml [project.entry-points."typeguard.checker_lookup_functions"] my_checker = "mymodule:my_checker_lookup" ``` -------------------------------- ### Configure Collection Checking Strategy Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/configuration.md Determine the thoroughness of type checking for collection elements. Choose between checking only the first item for speed or all items for complete validation. ```python from typeguard import check_type, CollectionCheckStrategy # Check only first item (fast) check_type( [1, 2, "three"], list[int], collection_check_strategy=CollectionCheckStrategy.FIRST_ITEM ) # Passes: first item is 1 (int) # Check all items (thorough) check_type( [1, 2, "three"], list[int], collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS ) # Raises: "three" is not int # Global configuration import typeguard typeguard.config.collection_check_strategy = CollectionCheckStrategy.ALL_ITEMS ``` -------------------------------- ### Check Type with FIRST_ITEM Strategy Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Use the FIRST_ITEM strategy for fast collection checking, which only verifies the first item in the collection. ```python from typeguard import check_type, CollectionCheckStrategy # Only checks first item - fast check_type( [1, 2, "three"], list[int], collection_check_strategy=CollectionCheckStrategy.FIRST_ITEM, ) # Passes (first item is 1, an int) ``` -------------------------------- ### Global Typeguard Configuration Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Set global configuration options for typeguard to apply consistently across your project. This includes default strategies for collection checking and error handling. ```python import typeguard typeguard.config.collection_check_strategy = CollectionCheckStrategy.ALL_ITEMS typeguard.config.typecheck_fail_callback = warn_on_error ``` -------------------------------- ### Instrument All Packages with Pytest Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/configuration.md Configures pytest to instrument all modules for type checking by using the special value ':all:' with the --typeguard-packages option. ```bash pytest --typeguard-packages=:all: ``` -------------------------------- ### Registering and Using the Plugin Programmatically Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/plugin-system.md This snippet demonstrates how to programmatically register a custom type checker lookup function and then use it with typeguard's check_type. It shows the import statements needed and the process of inserting the lookup function into the checker_lookup_functions list. ```python # register.py - Register plugin programmatically from typeguard import checker_lookup_functions from mymodule import custom_type_lookup, CustomType from typeguard import check_type # Register the plugin checker_lookup_functions.insert(0, custom_type_lookup) # Now type checking works with CustomType custom_obj = CustomType(42) check_type(custom_obj, CustomType) # Passes check_type("not a CustomType", CustomType) # Raises TypeCheckError ``` -------------------------------- ### Uninstall Import Hook Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/api-reference-classes.md Demonstrates how to manually uninstall an import hook using the uninstall() method. This is useful when the hook is no longer needed. ```python from typeguard import install_import_hook hook = install_import_hook(["myapp"]) # Hook is installed and active hook.uninstall() # Hook is removed; no more instrumentation ``` -------------------------------- ### Pytest Configuration for Typeguard Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/README.md Configure typeguard checks during pytest runs using command-line arguments. ```bash pytest --typeguard-packages=myapp --typeguard-collection-check-strategy=ALL_ITEMS ``` -------------------------------- ### Optimizing Checker Lookup Order Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/plugin-system.md Demonstrates how to manage the order of custom checker lookup functions. Place frequently used checkers at the beginning of the list for faster access. ```python from typeguard import checker_lookup_functions # Commonly used custom checker - add first checker_lookup_functions.insert(0, frequent_checker_lookup) # Less common checker - can be added later checker_lookup_functions.append(rare_checker_lookup) ``` -------------------------------- ### Type Checking with Custom Configuration Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/api-reference-decorators.md Illustrates using the @typechecked decorator with specific configuration options, such as enabling debug instrumentation. ```python from typeguard import typechecked # With custom configuration @typechecked(debug_instrumentation=True) def process_data(items: list[int]) -> list[str]: return [str(x) for x in items] ``` -------------------------------- ### Handle Forward References with WARN Policy Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/type-checking-guide.md Use `check_type` with `ForwardRefPolicy.WARN` to check types specified as strings, issuing a warning for unresolved references. ```python from typeguard import check_type, ForwardRefPolicy from typing import ForwardRef # String annotation (forward reference) check_type(obj, "MyClass", forward_ref_policy=ForwardRefPolicy.WARN) ``` -------------------------------- ### Per-Call Configuration for Collection Item Checking Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/type-checking-guide.md Configure type checking to verify all items within a collection on a per-call basis. This is useful when strict validation of collection contents is required for a specific function call. ```python from typeguard import check_type, CollectionCheckStrategy, warn_on_error # Check all items check_type( data, list[int], collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS, ) ``` -------------------------------- ### Instrument Packages with Pytest Source: https://github.com/agronholm/typeguard/blob/master/docs/userguide.md Use the `--typeguard-packages` option with pytest to instrument specified packages for type checking. ```bash pytest --typeguard-packages=foo.bar,xyz ``` -------------------------------- ### Checking for Unset Value Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/api-reference-classes.md Demonstrates how to check if a value is the unset sentinel to determine if a parameter was provided. ```python from typeguard import unset if some_value is unset: # Parameter was not provided use_default() ``` -------------------------------- ### get_stacklevel Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Calculates the appropriate stack level for issuing warnings, ensuring they point to the correct call site. ```APIDOC ## get_stacklevel() ### Description Get appropriate stack level for warnings. ### Signature ```python def get_stacklevel() -> int ``` ``` -------------------------------- ### Public API Variables Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Global variables and sentinels exposed by the package. ```APIDOC ## Variables ### `config` #### Description Global TypeCheckConfiguration (accessed via __getattr__). ### `checker_lookup_functions` #### Description List of registered checker functions. ### `Unset` #### Description Sentinel class. ### `unset` #### Description Sentinel value. ``` -------------------------------- ### Yield Value Checking Instrumentation for Generators Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/instrumentation.md Demonstrates the instrumentation applied to generators for checking the type of yielded values against their annotations. ```python # Original def gen(x: int): yield x yield "item" # After instrumentation (with yield type annotation) def gen(x: int): __typeguard_memo = TypeCheckMemo(...) check_type_internal(x, int, __typeguard_memo) __value = x __value = check_yield_type("gen", __value, int, __typeguard_memo) yield __value ``` -------------------------------- ### Per-Call Type Checking Configuration Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/README.md Configure type checking strategy and error callbacks for a single function call. ```python check_type(value, type, collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS, typecheck_fail_callback=warn_on_error, ) ``` -------------------------------- ### Typechecked Decorator Configuration Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/instrumentation.md Shows how to configure the instrumentation behavior using the `@typechecked` decorator with various policy and strategy options. ```python @typechecked( forward_ref_policy=ForwardRefPolicy.ERROR, collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS, debug_instrumentation=True, ) def my_function(x: int) -> int: return x ``` -------------------------------- ### Forward Reference Policy: WARN Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Use the WARN policy for default forward reference checking, which emits a TypeHintWarning if a reference cannot be resolved. ```python # Emits TypeHintWarning if reference can't be resolved check_type(obj, "UndefinedType", forward_ref_policy=ForwardRefPolicy.WARN) ``` -------------------------------- ### Global Configuration for Type Check Failure Callback Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/type-checking-guide.md Set a global callback function to handle type check failures, such as warning instead of raising errors. This provides a centralized mechanism for managing type error responses. ```python typeguard.config.typecheck_fail_callback = warn_on_error # All subsequent checks use this config ``` -------------------------------- ### Pytest Configuration in pyproject.toml Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Define pytest typeguard configurations within your `pyproject.toml` file. This allows for project-wide settings that are automatically applied during test runs. ```toml # pyproject.toml [tool.pytest.ini_options] typeguard-packages = ["myapp", "mylib"] typeguard-forward-ref-policy = "WARN" ``` -------------------------------- ### Implementing Caching for Expensive Lookups Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/plugin-system.md Shows how to use `functools.lru_cache` to cache results of expensive checker lookup functions. This requires converting types to cacheable representations. ```python from functools import lru_cache @lru_cache(maxsize=128) def expensive_checker_lookup(origin_type_id: int, args_tuple: tuple) -> TypeCheckerCallable | None: # Cached lookup logic pass def actual_checker_lookup(origin_type: Any, args: tuple[Any, ...], extras: tuple[Any, ...]) -> TypeCheckerCallable | None: # Convert to cacheable types origin_id = id(origin_type) args_tuple = tuple(id(arg) if isinstance(arg, type) else arg for arg in args) return expensive_checker_lookup(origin_id, args_tuple) ``` -------------------------------- ### TypeCheckConfiguration Class Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Configuration dataclass for Typeguard settings. ```APIDOC ## Class: TypeCheckConfiguration ### Description Configuration dataclass for Typeguard settings. ### Attributes - **forward_ref_policy**: Policy for handling forward references (e.g., `ForwardRefPolicy.ERROR`). - **collection_check_strategy**: Strategy for checking items in collections (e.g., `CollectionCheckStrategy.ALL_ITEMS`). ``` -------------------------------- ### Push Changeset to Fork Source: https://github.com/agronholm/typeguard/blob/master/docs/contributing.md Push your committed changes to your forked repository on GitHub. This makes your changes available for a pull request. ```bash git push ``` -------------------------------- ### Automatic Module Type Checking with Import Hook Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/type-checking-guide.md Use install_import_hook() to automatically instrument all functions within specified modules. This is suitable for comprehensive validation across entire codebases during development or testing. ```python from typeguard import typechecked, install_import_hook # Entire module via import hook hook = install_import_hook(["myapp"]) import myapp # All myapp functions are instrumented ``` -------------------------------- ### Public API Functions Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Runtime type checking and related utility functions available for direct use. ```APIDOC ## Functions ### `check_type()` #### Description Runtime type checking. ### `check_argument_types()` #### Description Check function arguments. ### `check_return_type()` #### Description Check return value. ### `warn_on_error()` #### Description Convert errors to warnings. ### `install_import_hook()` #### Description Install module import hook. ### `load_plugins()` #### Description Load checker plugins. ### `suppress_type_checks()` #### Description Suppress all type checking. ``` -------------------------------- ### Global Type Checking Configuration Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/README.md Set global configuration options for typeguard, such as the collection check strategy. ```python import typeguard typeguard.config.collection_check_strategy = CollectionCheckStrategy.ALL_ITEMS ``` -------------------------------- ### Type Checking with Warning Conversion Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/README.md Configure check_type to emit TypeCheckWarning instead of raising an error. ```python from typeguard import check_type, warn_on_error check_type(value, int, typecheck_fail_callback=warn_on_error) # Emits TypeCheckWarning instead of raising ``` -------------------------------- ### Public API Decorators Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/module-reference.md Decorators for instrumenting functions with type checking capabilities. ```APIDOC ## Decorators ### `@typechecked` #### Description Instrument function for type checking. ### `@typeguard_ignore` #### Description Mark function to skip instrumentation. ``` -------------------------------- ### ImportHookManager Class Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/quick-reference.md Manages the import hook for type checking. ```APIDOC ## Class: ImportHookManager ### Description Manages the import hook for type checking. Provides a handle to the hook. ``` -------------------------------- ### Manually Load Typeguard Plugins Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/plugin-system.md After disabling automatic plugin loading, you can manually load specific plugins by appending their lookup functions to `checker_lookup_functions`. This provides granular control over plugin activation. ```python # Or manually manage from typeguard import checker_lookup_functions, load_plugins # Don't auto-load # Then manually load only needed plugins from my_plugin import my_checker_lookup checker_lookup_functions.append(my_checker_lookup) ``` -------------------------------- ### Basic Function Type Checking Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/api-reference-decorators.md Demonstrates the basic usage of the @typechecked decorator on a regular Python function to enforce type annotations at runtime. ```python from typeguard import typechecked # Basic usage on a function @typechecked def greet(name: str, age: int) -> str: return f"{name} is {age} years old" ``` -------------------------------- ### Enable Debug Instrumentation Output Source: https://github.com/agronholm/typeguard/blob/master/_autodocs/configuration.md Activate debug instrumentation to print the instrumented source code of decorated or imported modules to stderr. This is useful for understanding how TypeGuard modifies code. ```python from typeguard import typechecked, TypeCheckConfiguration import typeguard # Per-function @typechecked(debug_instrumentation=True) def my_function(x: int) -> str: return str(x) # Prints instrumented code to stderr # Globally typeguard.config.debug_instrumentation = True # With import hook from typeguard import install_import_hook typeguard.config.debug_instrumentation = True hook = install_import_hook(["mymodule"]) import mymodule # Prints instrumented code for all mymodule functions ```