示例#1
0
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())
示例#2
0
文件: t.py 项目: int3l/explains
import functools
from typing import Callable
from typing import ParamSpec
from typing import TypeVar

P = ParamSpec('P')
R = TypeVar('R')


def prints_hi(f: Callable[P, R]) -> Callable[P, R]:
    @functools.wraps(f)
    def prints_hi_inner(*args: P.args, **kwargs: P.kwargs) -> R:
        print('ohai')
        return f(*args, **kwargs)

    return prints_hi_inner


@prints_hi
def hello(name: str) -> int:
    print(f'hello hello {name}')
    return 5


x = hello('anthony')
print(x)
示例#3
0
from __future__ import annotations
from collections.abc import Iterable
from functools import wraps
from inspect import Parameter, signature
from subprocess import CalledProcessError
from typing import TYPE_CHECKING

from .processing import identity
from core.runner import subprocess_run

if TYPE_CHECKING:
    from collections.abc import Callable, Collection, Mapping
    from typing import Any, cast, Optional, ParamSpec, TypeVar

    _P = ParamSpec("_P")
    _R = TypeVar("_R")


def command(
    executable: Iterable[str],
    flag_overrides: Optional[Mapping[str, str]] = None,
    flag_repeats: Optional[Collection[str]] = None,
    processing: Callable[[str], _R] = identity,
    check_returncode: bool = True
) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:
    flag_overrides = flag_overrides or {}
    flag_repeats = flag_repeats or set()

    def decorator(function: Callable[_P, _R]) -> Callable[_P, _R]:
        @wraps(function)
        def decorated(*args: _P.args, **kwargs: _P.kwargs) -> _R:
示例#4
0
# This sample tests error conditions for ParamSpec (PEP 612).

from typing import Any, Callable, List, ParamSpec, Protocol, Tuple, cast

TParams = ParamSpec("TParams")


# This should generate an error because ParamSpecs
# can't be used as a type annotation.
def foo(a: TParams) -> int:
    return 1


a = 3

# This should generate an error.
b = cast(TParams, a)

foo(1)


def func1(x: Callable[TParams, Any]):
    # This should generate an error.
    c: List[TParams] = []

    d: Callable[TParams, int]

    # This should generate an error.
    e: Callable[TParams, TParams]

    # This should generate an error.
示例#5
0
# This sample tests the type checker's handling of ParamSpec
# and Concatenate as described in PEP 612.

from typing import Callable, Concatenate, ParamSpec, TypeVar

P = ParamSpec("P")
R = TypeVar("R")


class Request:
    ...


def with_request(f: Callable[Concatenate[Request, P], R]) -> Callable[P, R]:
    def inner(*args: P.args, **kwargs: P.kwargs) -> R:
        return f(Request(), *args, **kwargs)

    return inner


@with_request
def takes_int_str(request: Request, x: int, y: str) -> int:
    # use request
    return x + 7


takes_int_str(1, "A")

# This should generate an error because the first arg
# is the incorrect type.
takes_int_str("B", "A")
from sdcm.wait import exponential_retry

LOGGER = logging.getLogger(__name__)

INSTANCE_PROVISION_ON_DEMAND = 'on_demand'
INSTANCE_PROVISION_SPOT_FLEET = 'spot_fleet'
INSTANCE_PROVISION_SPOT_LOW_PRICE = 'spot_low_price'
INSTANCE_PROVISION_SPOT_DURATION = 'spot_duration'
SPOT_CNT_LIMIT = 20
SPOT_FLEET_LIMIT = 50
SPOT_TERMINATION_CHECK_OVERHEAD = 15
LOCAL_CMD_RUNNER = LocalCmdRunner()
EBS_VOLUME = "attached"
INSTANCE_STORE = "instance_store"

P = ParamSpec("P")  # pylint: disable=invalid-name
R = TypeVar("R")  # pylint: disable=invalid-name

# pylint: disable=too-many-lines


class AWSCluster(cluster.BaseCluster):  # pylint: disable=too-many-instance-attributes,abstract-method,

    """
    Cluster of Node objects, started on Amazon EC2.
    """

    def __init__(self, ec2_ami_id, ec2_subnet_id, ec2_security_group_ids,  # pylint: disable=too-many-arguments
                 services, credentials, cluster_uuid=None,
                 ec2_instance_type='c5.xlarge', ec2_ami_username='******',
                 ec2_user_data='', ec2_block_device_mappings=None,
示例#7
0
# This sample tests the handling of class specialization expressions
# that provide signatures for ParamSpecs.

from typing import Any, Callable, Concatenate, Generic, Literal, ParamSpec, TypeVar


T = TypeVar("T")
P1 = ParamSpec("P1")
P2 = ParamSpec("P2")


class X(Generic[T, P1]):
    f: Callable[P1, int]
    x: T


def x1(x: X[int, P2]) -> str:
    ...


def x2(x: X[int, Concatenate[int, P2]]) -> str:
    ...


def X3(x: X[int, [int, bool]]) -> str:
    ...


def x4(x: X[int, ...]) -> str:
    ...
示例#8
0
    signature, )

from typing import (
    TypeVar,
    Callable,
)

from .exceptions import (
    PrototypeError, )

if sys.version_info >= (3, 10):
    from typing import ParamSpec
else:
    from typing_extensions import ParamSpec  # pragma: no cover

Parameters = ParamSpec("Parameters")
ReturnType = TypeVar("ReturnType")


# noinspection PyTypeHints
def prototype(
    proto: Callable[Parameters, ReturnType],
    /,
    *,
    runtime: bool = True,
) -> Callable[Parameters, ReturnType]:
    """
    Prototype decorator acts like a type protection shield
    that validates the parameters specification and return
    type annotation of the function against given prototype.
示例#9
0
# This sample tests error conditions for ParamSpec (PEP 612).

from typing import Callable, List, ParamSpec, Tuple, cast


TParams = ParamSpec("TParams")

# This should generate an error because ParamSpecs
# can't be used as a type annotation.
def foo(a: TParams) -> int:
    return 1


a = 3

# This should generate an error.
b = cast(TParams, a)

# This should generate an error.
foo(1)

# This should generate an error.
c: List[TParams] = []

d: Callable[TParams, int]

# This should generate an error.
e: Callable[TParams, TParams]

# This should generate an error.
f: Callable[[TParams], int]
示例#10
0
# Copyright (c) 2022 Tulir Asokan
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import annotations

from typing import Any
import functools

from mautrix import __optional_imports__

if __optional_imports__:
    from typing import Awaitable, Callable, ParamSpec

    Param = ParamSpec("Param")
    Func = Callable[Param, Awaitable[Any]]


def async_getter_lock(fn: Func) -> Func:
    """
    A utility decorator for locking async getters that have caches
    (preventing race conditions between cache check and e.g. async database actions).

    The class must have an ```_async_get_locks`` defaultdict that contains :class:`asyncio.Lock`s
    (see example for exact definition). Non-cache-affecting arguments should be only passed as
    keyword args.

    Args:
        fn: The function to decorate.
示例#11
0
# This sample tests a complicated combination of ParamSpec usage.

# pyright: strict

from typing import Any, Callable, Concatenate, ParamSpec, Protocol, TypeVar


_Fn = TypeVar("_Fn", bound=Callable[..., Any])
_Ret = TypeVar("_Ret")
_Args = ParamSpec("_Args")
_Self = TypeVar("_Self", bound="_GenerativeType")


def decorator(
    target: Callable[Concatenate[_Fn, _Args], _Ret]
) -> Callable[[_Fn], Callable[_Args, _Ret]]:
    ...


class _GenerativeType(Protocol):
    def _generate(self: "_Self") -> "_Self":
        ...


def generative(
    fn: Callable[Concatenate[_Self, _Args], None]
) -> Callable[Concatenate[_Self, _Args], _Self]:
    @decorator
    def _generative(
        fn: Callable[Concatenate[_Self, _Args], None],
        self: _Self,
示例#12
0
# This sample tests ParamSpec (PEP 612) behavior.

from typing import (
    Awaitable,
    Callable,
    Generic,
    Optional,
    ParamSpec,
    TypeVar,
    Union,
    overload,
)

Ps = ParamSpec("Ps")
R = TypeVar("R")


async def log_to_database():
    ...


def add_logging(f: Callable[Ps, R]) -> Callable[Ps, Awaitable[R]]:
    async def inner(*args: Ps.args, **kwargs: Ps.kwargs) -> R:
        await log_to_database()
        return f(*args, **kwargs)

    return inner


@add_logging
def foo(x: int, y: str) -> int:
示例#13
0
class BaseMixin:
    @pytest.fixture(autouse=True)
    def use_bot(self, bot: SpellBot) -> None:
        self.bot = bot

    @pytest.fixture(autouse=True)
    def use_settings(self, settings: Settings) -> None:
        self.settings = settings

    @pytest.fixture(autouse=True)
    def use_factories(self, factories: Factories) -> None:
        self.factories = factories


CogT = TypeVar("CogT", bound=commands.Cog)
CogCallbackP = ParamSpec("CogCallbackP")


class InteractionMixin(BaseMixin):
    interaction: discord.Interaction

    @pytest.fixture(autouse=True, name="interaction")
    def use_interaction(
            self, interaction: discord.Interaction) -> discord.Interaction:
        self.interaction = interaction
        return self.interaction

    @pytest.fixture
    def add_guild(self, factories: Factories) -> Callable[..., Guild]:
        return factories.guild.create
示例#14
0
    sprite_idx: float = _default()


@dataclass
class _LayerPolyOutput:
    vs_out: 'out_t'[_VS_OUT] = _out_t_default()


@dataclass
class _poly(_LayerUniform):
    ...


_buffer_type = _frag | _poly

_NamedFnP = ParamSpec('_NamedFnP')
_NamedFnR = TypeVar('_NamedFnR')
_NamedFnStage = Literal['frag', 'poly', 'any']


def lib(
    stage: _NamedFnStage
) -> Callable[[Callable[_NamedFnP, _NamedFnR]], Callable[_NamedFnP,
                                                         _NamedFnR]]:
    def deco(
            f: Callable[_NamedFnP,
                        _NamedFnR]) -> Callable[_NamedFnP, _NamedFnR]:
        def wrapper(_stage: _NamedFnStage = stage,
                    *args: _NamedFnP.args,
                    **kwargs: _NamedFnP.kwargs) -> _NamedFnR:
            return f(*args, **kwargs)