How to use the typing.Set function in typing

To help you get started, we’ve selected a few typing examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github icon-project / icon-service / tests / prep / test_prep_container.py View on Github external
def test_get_by_index(create_prep_container):
    size = 10
    preps = create_prep_container(size)

    old_preps: Set['PRep'] = set()

    # Index
    for i in range(size):
        prep: 'PRep' = preps.get_by_index(i)
        assert prep is not None
        assert preps not in old_preps
        old_preps.add(prep)

    prep = preps.get_by_index(size)
    assert prep is None

    # Reverse index
    for i in range(1, size + 1):
        prep = preps.get_by_index(-i)
        assert prep is not None
        assert prep == preps.get_by_index(size - i)
github Shopify / shopify_python / shopify_python / git_utils.py View on Github external
('aggressive', int),
    ('diff', bool),
    ('exclude', typing.Set[typing.List[str]]),
    ('experimental', bool),
    ('global_config', typing.Optional[typing.List[str]]),
    ('ignore', str),
    ('ignore_local_config', bool),
    ('in_place', bool),
    ('indent_size', int),
    ('jobs', int),
    ('line_range', typing.Optional[typing.Sequence]),
    ('list_fixes', bool),
    ('max_line_length', int),
    ('pep8_passes', int),
    ('recursive', bool),
    ('select', typing.Set[str]),
    ('verbose', int),
    ('hang_closing', bool),
])


def autopep_files(files, max_line_length):
    # type: (typing.List[str], int) -> None
    files = files[:]
    options = _AutopepOptions(aggressive=1,  # pylint:disable=not-callable
                              diff=False,
                              exclude=set(),
                              experimental=False,
                              global_config=None,
                              ignore='',
                              ignore_local_config=False,
                              in_place=True,
github coverdrive / MDP-DP-RL / src / algorithms / adp / adp.py View on Github external
softmax: bool,
        epsilon: float,
        epsilon_half_life: float,
        tol: float,
        fa_spec: FuncApproxSpec
    ) -> None:
        self.mdp_rep: MDPRepForADP = mdp_rep_for_adp
        self.num_samples: int = num_samples
        self.softmax: bool = softmax
        self.epsilon_func: Callable[[int], float] = get_epsilon_decay_func(
            epsilon,
            epsilon_half_life
        )
        self.tol: float = tol
        self.fa: FuncApproxBase = fa_spec.get_vf_func_approx_obj()
        self.state_action_func: Callable[[S], Set[A]] =\
            self.mdp_rep.state_action_func
github dagster-io / dagster / python_modules / dagster / dagster / core / types / dagster_type.py View on Github external
from .typing_api import (
    is_closed_python_dict_type,
    is_closed_python_set_type,
    is_closed_python_tuple_type,
)
from .wrapping import WrappingType

MAGIC_RUNTIME_TYPE_NAME = '__runtime_type'


def is_runtime_type_decorated_klass(klass):
    check.type_param(klass, 'klass')
    return hasattr(klass, MAGIC_RUNTIME_TYPE_NAME)


OPEN_CONTAINER_TYPES = {dict, Dict, typing.Dict, tuple, typing.Tuple, set, typing.Set}


def check_dagster_type_param(dagster_type, param_name, base_type):

    # Cannot check base_type because of circular references and no fwd declarations
    if dagster_type is None:
        return dagster_type
    if dagster_type in OPEN_CONTAINER_TYPES:
        return dagster_type
    if is_closed_python_dict_type(dagster_type):
        return dagster_type
    if is_closed_python_tuple_type(dagster_type):
        return dagster_type
    if is_closed_python_set_type(dagster_type):
        return dagster_type
    if BuiltinEnum.contains(dagster_type):
github ICTU / quality-report / backend / hqlib / report / report.py View on Github external
def __init__(self, project: domain.Project) -> None:
        # Use None as name to keep the history consistent of metrics that have the report as subject:
        super().__init__(name='None')
        self.__project = project
        self.__products = sorted(project.products(), key=lambda product: (product.name(), product.short_name()))
        self.__sections: Sequence[Section] = []
        self.__metrics: List[domain.Metric] = []
        self.__requirements: Set[Type[domain.Requirement]] = set()
github upsidetravel / graphene-pydantic / graphene_pydantic / converters.py View on Github external
"""
    origin = type_.__origin__
    if not origin:  # pragma: no cover  # this really should be impossible
        raise ConversionError(f"Don't know how to convert type {type_!r} ({field})")

    # NOTE: This is a little clumsy, but working with generic types is; it's hard to
    # decide whether the origin type is a subtype of, say, T.Iterable since typical
    # Python functions like `isinstance()` don't work
    if origin == T.Union:
        return convert_union_type(
            type_, field, registry, parent_type=parent_type, model=model
        )
    elif origin in (
        T.Tuple,
        T.List,
        T.Set,
        T.Collection,
        T.Iterable,
        list,
        set,
    ) or issubclass(origin, collections.abc.Sequence):
        # TODO: find a better way of divining that the origin is sequence-like
        inner_types = getattr(type_, "__args__", [])
        if not inner_types:  # pragma: no cover  # this really should be impossible
            raise ConversionError(
                f"Don't know how to handle {type_} (generic: {origin})"
            )
        # Of course, we can only return a homogeneous type here, so we pick the
        # first of the wrapped types
        inner_type = inner_types[0]
        return List(
            find_graphene_type(
github nunoloureiro / birdtradebot / birdtradebot / run.py View on Github external
def update_accounts_positions(accounts: Dict[str, Account], q: queue.Queue):
    """
        This function runs in a separate thread. It receives requests in the
        queue from the main thread. It places orders on the exchange so that
        each "pending pair" transitions to the position indicated by a specific
        tweet.
    """
    pairs: Dict[str, Set[str]] = {}
    new_pairs: Dict[str, Set[str]] = {}

    log.info("Exchange thread starting...")
    while True:
        while True:
            block = not pairs and not new_pairs
            try:
                if block:
                    log.debug("Exchange thread blocked until orders arrive...")
                account_name, product_id = q.get(block)
            except queue.Empty:
                break
            else:
                if account_name not in new_pairs:
                    new_pairs[account_name] = set()
                new_pairs[account_name].add(product_id)
github allenai / allennlp-semparse / allennlp_semparse / domain_languages / domain_language.py View on Github external
def get_nonterminal_productions(self) -> Dict[str, List[str]]:
        """
        Induces a grammar from the defined collection of predicates in this language and returns
        all productions in that grammar, keyed by the non-terminal they are expanding.

        This includes terminal productions implied by each predicate as well as productions for the
        `return type` of each defined predicate.  For example, defining a "multiply" predicate adds
        a " -> multiply" terminal production to the grammar, and `also` a "int ->
        [, int, int]" non-terminal production, because I can use the "multiply"
        predicate to produce an int.
        """
        if not self._nonterminal_productions:
            actions: Dict[str, Set[str]] = defaultdict(set)
            # If you didn't give us a set of valid start types, we'll assume all types we know
            # about (including functional types) are valid start types.
            if self._start_types:
                start_types = self._start_types
            else:
                start_types = set()
                for type_list in self._function_types.values():
                    start_types.update(type_list)
            for start_type in start_types:
                actions[START_SYMBOL].add(f"{START_SYMBOL} -> {start_type}")
            for name, function_type_list in self._function_types.items():
                for function_type in function_type_list:
                    actions[str(function_type)].add(f"{function_type} -> {name}")
                    if isinstance(function_type, FunctionType):
                        return_type = function_type.return_type
                        arg_types = function_type.argument_types
github roy2220 / async-pbrpc / async_pbrpc / server.py View on Github external
def __init__(self, host_name: str, port_number: int, *,
        loop: typing.Optional[asyncio.AbstractEventLoop]=None,
        logger: typing.Optional[logging.Logger]=None,
        transport_policy: typing.Optional[TransportPolicy]=None,
    ) -> None:
        dummy_transport = Transport(loop, logger, transport_policy)
        self._loop = dummy_transport.get_loop()
        self._logger = dummy_transport.get_logger()
        self._transport_policy = dummy_transport.get_policy()
        self._address = host_name, port_number
        self._channels: typing.Set[ServerChannel] = set()
        self._starting: typing.Optional[utils.Future[None]] = None
        self._running: asyncio.Future[None] = utils.make_done_future(self._loop)
        self._is_stopping = 0
        self._version = 0
        self.on_initialize()