def test_callable_with_paramspec(): P = ParamSpec("P") func_type = Callable[P, None] strategy = st.from_type(func_type) with pytest.raises( InvalidArgument, match= "Hypothesis can't yet construct a strategy for instances of a Callable type", ): strategy.example() with pytest.raises(InvalidArgument, match="Cannot register generic type"): st.register_type_strategy(func_type, st.none())
# This sample tests the matching of nested callables that each use # ParamSpec. from typing import Callable, Generic, Literal, TypeVar from typing_extensions import Concatenate, ParamSpec P = ParamSpec("P") Q = ParamSpec("Q") T = TypeVar("T") U = TypeVar("U") class Foo(Generic[P, T, Q, U]): ... def foo(func: Callable[Concatenate[Callable[P, T], Q], U]) -> Foo[P, T, Q, U]: ... @foo def bar(func: Callable[[int], float], a: str) -> bool: ... t1: Literal["Foo[(_p0: int), float, (a: str), bool]"] = reveal_type(bar)
"""Utilities for Plugwise.""" from collections.abc import Awaitable, Callable, Coroutine from typing import Any, TypeVar from plugwise.exceptions import PlugwiseException from typing_extensions import Concatenate, ParamSpec from homeassistant.exceptions import HomeAssistantError from .entity import PlugwiseEntity _P = ParamSpec("_P") _R = TypeVar("_R") _T = TypeVar("_T", bound=PlugwiseEntity) def plugwise_command( func: Callable[Concatenate[_T, _P], Awaitable[_R]] # type: ignore[misc] ) -> Callable[Concatenate[_T, _P], Coroutine[Any, Any, _R]]: # type: ignore[misc] """Decorate Plugwise calls that send commands/make changes to the device. A decorator that wraps the passed in function, catches Plugwise errors, and requests an coordinator update to update status of the devices asap. """ async def handler(self: _T, *args: _P.args, **kwargs: _P.kwargs) -> _R: try: return await func(self, *args, **kwargs) except PlugwiseException as error: raise HomeAssistantError( f"Error communicating with API: {error}") from error
from .. import exceptions from ..client import TrezorClient from ..transport import get_transport from ..ui import ClickUI, ScriptUI if TYPE_CHECKING: from ..transport import Transport from ..ui import TrezorClientUI # Needed to enforce a return value from decorators # More details: https://www.python.org/dev/peps/pep-0612/ from typing import TypeVar from typing_extensions import ParamSpec, Concatenate P = ParamSpec("P") R = TypeVar("R") class ChoiceType(click.Choice): def __init__(self, typemap: Dict[str, Any]) -> None: super().__init__(list(typemap.keys())) self.typemap = typemap def convert(self, value: str, param: Any, ctx: click.Context) -> Any: if value in self.typemap.values(): return value value = super().convert(value, param, ctx) return self.typemap[value]
Optional, TypeVar, Union, cast, ) # import autoimport import isort import setuptools import toml import typer from charmonium.async_subprocess import run from termcolor import cprint from typing_extensions import ParamSpec Params = ParamSpec("Parms") Return = TypeVar("Return") def coroutine_to_function( coroutine: Callable[Params, Awaitable[Return]] # type: ignore ) -> Callable[Params, Return]: # type: ignore @wraps(coroutine) def wrapper(*args: Params.args, **kwargs: Params.kwargs) -> Return: # type: ignore return asyncio.run(coroutine(*args, **kwargs)) # type: ignore return wrapper if TYPE_CHECKING:
import cProfile from functools import wraps from typing import Callable, TypeVar from typing_extensions import ParamSpec ParamT = ParamSpec("ParamT") ReturnT = TypeVar("ReturnT") def profiled(func: Callable[ParamT, ReturnT]) -> Callable[ParamT, ReturnT]: """ This decorator should obviously be used only in a dev environment. It works best when surrounding a function that you expect to be called once. One strategy is to write a backend test and wrap the test case with the profiled decorator. You can run a single test case like this: # edit zerver/tests/test_external.py and place @profiled above the test case below ./tools/test-backend zerver.tests.test_external.RateLimitTests.test_ratelimit_decrease Then view the results like this: ./tools/show-profile-results test_ratelimit_decrease.profile """ @wraps(func) def wrapped_func(*args: ParamT.args, **kwargs: ParamT.kwargs) -> ReturnT: fn = func.__name__ + ".profile"
if TYPE_CHECKING: from functools import cached_property as cached_property from typing_extensions import ParamSpec from .permissions import Permissions from .abc import Snowflake from .invite import Invite from .template import Template class _RequestLike(Protocol): headers: Mapping[str, Any] P = ParamSpec('P') else: cached_property = _cached_property T = TypeVar('T') T_co = TypeVar('T_co', covariant=True) _Iter = Union[Iterator[T], AsyncIterator[T]] class CachedSlotProperty(Generic[T, T_co]): def __init__(self, name: str, function: Callable[[T], T_co]) -> None: self.name = name self.function = function self.__doc__ = getattr(function, '__doc__')
α: _cdvann(Unit(), 'fine-structure constant') G: _cdvann(N * m**2 / kg**2, 'Newtonian constant of gravitation') m_p: _cdvann(kg, 'proton mass') m_n: _cdvann(kg, 'neutron mass') m_e: _cdvann(kg, 'electron mass') u: _cdvann(kg, 'atomic mass constant') _cdvanns = { key: get_args(ann)[1:] for key, ann in get_type_hints(CODATA_vals, include_extras=True).items() } _T = TypeVar('_T') _T1 = TypeVar('_T1') _PS = ParamSpec('_PS') _CODATA: TypeAlias = 'CODATA' # noinspection PyUnusedLocal def cast_( typ: Type[_T] ) -> Callable[[Callable[[_PS], _T1]], Union[Type[_T1], Callable[[_PS], _T]]]: def f(cls): return cls return f class cached_constant_property_base(cached_property, Generic[_T]): pass
# This sample tests the case where a ParamSpec is used within a source # and destination callback protocol. from typing import Callable, Protocol from typing_extensions import Concatenate, ParamSpec P1 = ParamSpec("P1") P2 = ParamSpec("P2") P3 = ParamSpec("P3") P4 = ParamSpec("P4") class Context: ... class Response: ... class ContextCallback(Protocol[P1]): def __call__(self, ctx: Context, /, *args: P1.args, **kwargs: P1.kwargs) -> Response: ... def call_context_callback(callback: ContextCallback[P3], /, *args: P3.args, **kwargs: P3.kwargs) -> Response: ...
'HybridCommand', 'HybridGroup', 'hybrid_command', 'hybrid_group', ) T = TypeVar('T') U = TypeVar('U') CogT = TypeVar('CogT', bound='Cog') CommandT = TypeVar('CommandT', bound='Command') # CHT = TypeVar('CHT', bound='Check') GroupT = TypeVar('GroupT', bound='Group') _NoneType = type(None) if TYPE_CHECKING: P = ParamSpec('P') P2 = ParamSpec('P2') CommandCallback = Union[Callable[Concatenate[CogT, ContextT, P], Coro[T]], Callable[Concatenate[ContextT, P], Coro[T]], ] else: P = TypeVar('P') P2 = TypeVar('P2') class _CallableDefault: __slots__ = ('func', ) def __init__(self, func: Callable[[Context], Any]) -> None: self.func: Callable[[Context], Any] = func
import functools import textwrap from typing import Any from typing import Callable from typing import Optional from typing import TypeVar import warnings from typing_extensions import ParamSpec from optuna.exceptions import ExperimentalWarning FT = TypeVar("FT") FP = ParamSpec("FP") CT = TypeVar("CT") _EXPERIMENTAL_NOTE_TEMPLATE = """ .. note:: Added in v{ver} as an experimental feature. The interface may change in newer versions without prior notice. See https://github.com/optuna/optuna/releases/tag/v{ver}. """ def _validate_version(version: str) -> None: if not isinstance(version, str) or len(version.split(".")) != 3: raise ValueError( "Invalid version specification. Must follow `x.y.z` format but `{}` is given" .format(version))
Optional, Tuple, Type, Union, cast, Iterable, AsyncContextManager, TypeVar, ) if sys.version_info >= (3, 7): from contextlib import asynccontextmanager else: from async_generator import asynccontextmanager as _asynccontextmanager # type: ignore from typing_extensions import ParamSpec _P = ParamSpec('_P') _T = TypeVar('_T') def asynccontextmanager( func: Callable[_P, AsyncIterator[_T]] ) -> Callable[_P, AsyncContextManager[_T]]: # type: ignore return _asynccontextmanager(func) import paho.mqtt.client as mqtt # type: ignore from paho.mqtt.properties import Properties from .error import MqttCodeError, MqttConnectError, MqttError from .types import PayloadType, T MQTT_LOGGER = logging.getLogger("mqtt")
from opentelemetry.trace import Span from opentelemetry.util import types from typing_extensions import ParamSpec # pylint:disable=ungrouped-imports from .config import LOGGER __all__ = ["LOGGER"] LEGAL_ATTR_BASE_TYPES = (str, bool, int, float) # Types ################################################################################ # https://stackoverflow.com/a/65681776 # https://stackoverflow.com/a/71324646 T = TypeVar("T") # the callable/awaitable return type P = ParamSpec("P") # the callable parameters # NOTE: 'mypy' is behind 'typing' when it comes to a few things (hence the '# type: ignore's) # (1) Parsing ParamSpec: # https://github.com/python/typing/issues/794 # https://github.com/python/mypy/issues/8645 # (2) Encapsulating an async-func, generator, & sync-func as a single generic # Classes/Functions #################################################################### class FunctionInspector: """A wrapper around a function and its introspection functionalities.""" def __init__(self, func: Callable[P, T], args: P.args, kwargs: P.kwargs): # type: ignore[name-defined] bound_args = inspect.signature(func).bind(*args, **kwargs)
# This sample tests the case where a Callable that includes a Concatenate # is assigned to a ParamSpec that doesn't include a Concatenate. from typing import Callable, Literal, TypeVar from typing_extensions import Concatenate, ParamSpec Pi = ParamSpec("Pi") def is_inty(f: Callable[Pi, object]) -> Callable[Pi, int]: ... Po = ParamSpec("Po") T = TypeVar("T") def outer(f: Callable[Concatenate[str, Po], object]): x = is_inty(f) t_x: Literal["(str, **Po@outer) -> int"] = reveal_type(x)
from __future__ import annotations import tempfile from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Generic, Optional, TypeVar, Union, cast _T = TypeVar("_T") # Thanks Eric Traut # https://github.com/microsoft/pyright/discussions/1763#discussioncomment-617220 if TYPE_CHECKING: # ParamSpec is just for type checking, hence pylint disable from typing_extensions import ParamSpec # pylint: disable=no-name-in-module FuncParams = ParamSpec("FuncParams") else: FuncParams = TypeVar("FuncParams") FuncReturn = TypeVar("FuncReturn") class Constant(Generic[FuncParams, FuncReturn]): def __init__(self, val: FuncReturn): self.val = val def __repr__(self) -> str: return f"Constant({self.val!r})" def __call__(self, *args: FuncParams.args, **kwargs: FuncParams.kwargs) -> FuncReturn: return self.val
from inspect import Signature from typing import TYPE_CHECKING, TypeVar, Type, Generic, Callable, Optional import progressbar import logging import time from ..misc.plugins import PluginVendor, VendorPreset from ..misc.ux import deprecated if TYPE_CHECKING: from ..knowledge_base import KnowledgeBase import angr from ..project import Project from typing_extensions import ParamSpec AnalysisParams = ParamSpec("AnalysisParams") l = logging.getLogger(name=__name__) class AnalysisLogEntry: def __init__(self, message, exc_info=False): if exc_info: (e_type, value, traceback) = sys.exc_info() self.exc_type = e_type self.exc_value = value self.exc_traceback = traceback else: self.exc_type = None self.exc_value = None self.exc_traceback = None