### FlexibleAlias for Generic Type Aliases in mypy_extensions Source: https://context7.com/python/mypy_extensions/llms.txt Demonstrates the use of FlexibleAlias for creating generic type aliases that can accommodate extra type parameters. This is useful for advanced typing scenarios where parameters might be ignored. ```python from mypy_extensions import FlexibleAlias from typing import TypeVar, List T = TypeVar('T') # Create a flexible alias that ignores extra type parameters # FlexibleAlias[T, List[T]] creates an alias where extra params are dropped MyList = FlexibleAlias[T, List[T]] # Usage in type hints (the extra parameter is accepted but ignored at runtime) def process_items(items: MyList[int]) -> int: return sum(items) result = process_items([1, 2, 3, 4, 5]) print(result) # 15 ``` -------------------------------- ### Variadic Keyword Arguments (KwArg) with mypy_extensions Source: https://context7.com/python/mypy_extensions/llms.txt Demonstrates using KwArg from mypy_extensions to define function types that accept variable keyword arguments. This allows for more precise type hinting of functions with dynamic keyword parameters. ```python from typing import Callable from mypy_extensions import KwArg # Function type accepting variable keyword arguments ConfigBuilderType = Callable[[KwArg(str)], dict] def build_config(**options: str) -> dict: return {k: v for k, v in options.items()} def setup(builder: ConfigBuilderType) -> None: config = builder(host="localhost", port="8080", debug="true") print(config) # {'host': 'localhost', 'port': '8080', 'debug': 'true'} setup(build_config) ``` -------------------------------- ### TypedDict Definition and Usage (Deprecated) Source: https://context7.com/python/mypy_extensions/llms.txt Demonstrates how to define dictionary types with fixed keys and specific value types using `mypy_extensions.TypedDict`. Note that this feature is deprecated in favor of standard library or `typing_extensions` equivalents. It shows both functional and class-based syntax, instance creation, and accessing annotations. ```python import warnings from mypy_extensions import TypedDict # Suppress deprecation warnings for demonstration warnings.filterwarnings("ignore", category=DeprecationWarning) # Functional syntax with dictionary Employee = TypedDict('Employee', {'name': str, 'id': int, 'department': str}) # Functional syntax with keyword arguments Point = TypedDict('Point', x=int, y=int) # Class syntax (Python 3.6+) class UserProfile(TypedDict): username: str email: str age: int # Creating instances (returns regular dict at runtime) emp = Employee(name='Alice', id=42, department='Engineering') print(emp) # {'name': 'Alice', 'id': 42, 'department': 'Engineering'} print(type(emp)) # # Access annotations print(Employee.__annotations__) # {'name': , 'id': , 'department': } print(Employee.__total__) # True # Optional fields with total=False class OptionalConfig(TypedDict, total=False): debug: bool log_level: int log_path: str config = OptionalConfig() # Empty dict is valid config_with_debug = OptionalConfig(debug=True) # Partial dict is valid print(config) # {} print(config_with_debug) # {'debug': True} ``` -------------------------------- ### VarArg: Type Hint for Variadic Positional Arguments (*args) Source: https://context7.com/python/mypy_extensions/llms.txt Defines a type hint for functions that accept an arbitrary number of positional arguments. `mypy_extensions.VarArg` is used within `typing.Callable` to specify the type of elements within the `*args` tuple, allowing mypy to check the types of all passed positional arguments. ```python from typing import Callable from mypy_extensions import VarArg # Function type accepting variable positional arguments SumFunctionType = Callable[[VarArg(int)], int] def sum_all(*numbers: int) -> int: return sum(numbers) def calculate(fn: SumFunctionType) -> None: print(fn(1, 2, 3)) # 6 print(fn(10, 20, 30, 40)) # 100 calculate(sum_all) ``` -------------------------------- ### Native Integer Types for mypyc Compilation Source: https://context7.com/python/mypy_extensions/llms.txt Introduces native integer types (i64, i32, i16, u8) from mypy_extensions for mypyc-compiled code. These types represent fixed-width integers for performance, behaving like standard Python ints at runtime. ```python from mypy_extensions import i64, i32, i16, u8 # Construction - behaves like int() a = i64(100) b = i32(-50) c = i16(255) d = u8(42) print(a, b, c, d) # 100 -50 255 42 print(type(a)) # # From string with base hex_val = i64("ff", 16) bin_val = i32("1010", base=2) print(hex_val) # 255 print(bin_val) # 10 # From float (truncates) from_float = i64(3.7) print(from_float) # 3 # isinstance checks (matches int behavior at runtime) print(isinstance(100, i64)) # True print(isinstance(100, i32)) # True print(isinstance(100, u8)) # True print(isinstance(3.14, i64)) # False # Type annotations for mypyc-compiled code def fast_compute(x: i64, y: i64) -> i64: return i64(x * y + 1) result = fast_compute(i64(10), i64(20)) print(result) # 201 ``` -------------------------------- ### Using the 'trait' Decorator for mypyc Classes Source: https://context7.com/python/mypy_extensions/llms.txt Explains the @trait decorator from mypy_extensions, used to mark classes as traits for mypyc compilation. At runtime, it functions as a no-op, returning the class unchanged. ```python from mypy_extensions import trait @trait class Drawable: def draw(self) -> None: pass @trait class Clickable: def on_click(self) -> None: pass # In mypyc-compiled code, traits enable efficient multiple inheritance class Button(Drawable, Clickable): def draw(self) -> None: print("Drawing button") def on_click(self) -> None: print("Button clicked") btn = Button() btn.draw() # Drawing button btn.on_click() # Button clicked ``` -------------------------------- ### DefaultNamedArg: Type Hint for Optional Keyword-Only Arguments Source: https://context7.com/python/mypy_extensions/llms.txt Enables type hinting for callables that accept keyword-only arguments with default values. `mypy_extensions.DefaultNamedArg` is used within `typing.Callable` to specify the type, name, and default value of optional keyword arguments, improving type safety for flexible function signatures. ```python from typing import Callable from mypy_extensions import DefaultNamedArg # Callback with optional keyword-only argument LoggerType = Callable[[str, DefaultNamedArg(str, 'level')], None] def log_message(msg: str, *, level: str = "INFO") -> None: print(f"[{level}] {msg}") def run_with_logger(logger: LoggerType) -> None: logger("Starting process") # [INFO] Starting process logger("Error occurred", level="ERROR") # [ERROR] Error occurred run_with_logger(log_message) ``` -------------------------------- ### Applying 'mypyc_attr' Decorator with mypy_extensions Source: https://context7.com/python/mypy_extensions/llms.txt Details the @mypyc_attr decorator for applying mypyc-specific attributes to classes or functions. This decorator is a runtime no-op, affecting only mypyc compilation behavior. ```python from mypy_extensions import mypyc_attr # Mark a class for specific mypyc behavior @mypyc_attr(allow_interpreted_subclasses=True) class BasePlugin: def execute(self) -> str: return "base" # Can be subclassed even from non-compiled code class CustomPlugin(BasePlugin): def execute(self) -> str: return "custom" plugin = CustomPlugin() print(plugin.execute()) # custom # Multiple attributes @mypyc_attr(serializable=True, allow_interpreted_subclasses=True) class DataModel: def __init__(self, value: int) -> None: self.value = value model = DataModel(42) print(model.value) # 42 ``` -------------------------------- ### Arg: Type Hint for Required Positional Arguments Source: https://context7.com/python/mypy_extensions/llms.txt Defines a type hint for a callable that expects a single, required positional argument of a specific type. The `Arg` constructor from `mypy_extensions` is used within a `typing.Callable` to specify the argument's type and name, aiding mypy in type checking. ```python from typing import Callable from mypy_extensions import Arg # Function that takes a callback with a required positional 'x' argument def process(callback: Callable[[Arg(int, 'x')], str]) -> str: return callback(42) def my_callback(x: int) -> str: return f"Received: {x}" result = process(my_callback) print(result) # Received: 42 ``` -------------------------------- ### DefaultArg: Type Hint for Positional Arguments with Defaults Source: https://context7.com/python/mypy_extensions/llms.txt Specifies a type hint for a callable that accepts a positional argument which has a default value. `mypy_extensions.DefaultArg` is used within `typing.Callable` to denote the type, name, and default nature of the argument, enabling mypy to understand optional positional parameters. ```python from typing import Callable from mypy_extensions import DefaultArg # Callback type where 'count' has a default value ProcessorType = Callable[[str, DefaultArg(int, 'count')], list] def repeat_string(text: str, count: int = 3) -> list: return [text] * count def use_processor(fn: ProcessorType) -> None: print(fn("hello")) # Uses default: ['hello', 'hello', 'hello'] print(fn("world", 2)) # Override: ['world', 'world'] use_processor(repeat_string) ``` -------------------------------- ### NamedArg: Type Hint for Keyword-Only Arguments Source: https://context7.com/python/mypy_extensions/llms.txt Provides a type hint for callables that require specific keyword-only arguments. `mypy_extensions.NamedArg` is used within `typing.Callable` to define the type and name of these arguments, ensuring they are passed by keyword and are mandatory. ```python from typing import Callable from mypy_extensions import NamedArg # Function type with keyword-only argument FormatterType = Callable[[str, NamedArg(bool, 'uppercase')], str] def format_text(text: str, *, uppercase: bool) -> str: return text.upper() if uppercase else text.lower() def apply_formatter(fn: FormatterType, value: str) -> None: print(fn(value, uppercase=True)) # HELLO print(fn(value, uppercase=False)) # hello apply_formatter(format_text, "Hello") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.