我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用typing.TypeVar()。
def get(self, name): # Two way mapping refname = Schema.referenceName(name) if refname not in self: result = TypeVar(refname) self[refname] = result self[result] = refname return self[refname]
def do_explode(self, kind): if kind in basic_types or type(kind) is typing.TypeVar: return False if not issubclass(kind, (typing.Sequence, typing.Mapping)): self.clear() self.extend(Args(kind)) return True return False
def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[TypeVar('S')]]: join_population = population + offspring_population return RankingAndCrowdingDistanceSelection(self.population_size).execute(join_population)
def _write_TypeVar(tpv, lines, inc=0): args = [tpv.__name__] if not tpv.__bound__ is None: args.append('bound='+type_util.type_str(tpv.__bound__)) if tpv.__covariant__: args.append('covariant=True') if tpv.__contravariant__: args.append('contravariant=True') lines.append("%s%s = TypeVar('%s')"%(inc*indent, tpv.__name__, ', '.join(args)))
def check_type(value: typing.Any, hint: typing.Optional[type]) -> bool: """Check given ``value``'s type. :param value: given argument :param hint: expected type of given ``value``. as like :mod:`typing` interprets, :const:`None` is interpreted as :class:`types.NoneType` :type hint: :class:`typing.Optional`[:class:`type`] """ if hint is None: hint = NoneType actual_type = type(value) if hint is NoneType: correct = value is None elif hint is typing.Any: correct = True elif hint is typing.Pattern or hint is typing.Match: correct = isinstance(value, hint.impl_type) elif isinstance(hint, typing.TypeVar): # TODO: Check generic correct = True elif issubclass(hint, typing.Callable): actual_type, correct = check_callable(value, hint) elif issubclass(hint, typing.Tuple): actual_type, correct = check_tuple(value, hint) elif issubclass(hint, typing.Union): actual_type, correct = check_union(value, hint) else: correct = isinstance(value, hint) return actual_type, correct
def test_alias_typevar(self) -> None: pyi_txt = """ from typing import TypeVar _T = TypeVar('_T', bound=str) SOME_GLOBAL: int def fun(error: _T) -> _T: ... """ src_txt = """ "Docstring" from __future__ import print_function import sys SOME_GLOBAL: int = 0 def fun(error): return error """ expected_txt = """ "Docstring" from __future__ import print_function import sys from typing import TypeVar SOME_GLOBAL: int = 0 _T = TypeVar('_T', bound=str) def fun(error: _T) -> _T: return error """ self.assertReapply(pyi_txt, src_txt, expected_txt) self.assertReapplyVisible(pyi_txt, src_txt, expected_txt)
def test_alias_typevar_typing(self) -> None: pyi_txt = """ import typing.foo.bar _T = typing.foo.bar.TypeVar('_T', bound=str) SOME_GLOBAL: int def fun(error: _T) -> _T: ... """ src_txt = """ "Docstring" import sys SOME_GLOBAL: int = 0 def fun(error): return error """ expected_txt = """ "Docstring" import sys import typing.foo.bar SOME_GLOBAL: int = 0 _T = typing.foo.bar.TypeVar('_T', bound=str) def fun(error: _T) -> _T: return error """ self.assertReapplyVisible(pyi_txt, src_txt, expected_txt)
def get_order_types() -> TypeVar: """Return valid order types for type annotations.""" return TypeVar('A', Order, MarketOrder, StopOrder, LimitOrder, StopLimitOrder)
def test_set_env(variables_dict): """Test environment setting visitors""" program = cs._parse_dictionary_to_program(variables_dict) module, _ = cs._parse_text(program) # get list of variable names in locals local_values = [module.type_environment.locals[name] for name in module.type_environment.locals] global_values = [module.type_environment.globals[name] for name in module.type_environment.globals] # verify the type of the value of each variable in the environment for value in local_values: assert isinstance(value, TypeVar) for value in global_values: assert isinstance(value, TypeVar)
def mismatching_types_messages(action, annotations, arg_values, arg_types) -> str: messages = [] for (arg_value, arg_type, (arg_name, annotation)) in zip(arg_values, arg_types, annotations.items()): if annotation == Any or isinstance(annotation, TypeVar): continue if arg_type != annotation: messages.append(f'Type mistmach for function `{action.__name__}`') messages.append( f'You tried to give me a `{arg_type}` but I wanted a `{annotation}` for the arg `{arg_name}`!' # noqa: E501 ) return '\n'.join(messages)
def test_invalid_typevar_bound(bound): T = TypeVar('T', bound=bound) pytest.raises_regexp(ValueError, 'invalid typevar bound', Handler, T)
def test_invalid_typevar_constraint(constraint): T = TypeVar('T', int, constraint) pytest.raises_regexp(ValueError, 'invalid typevar constraint', Handler, T)
def _write_class(clss, lines, inc = 0, assumed_globals=None, implicit_globals=None, assumed_typevars=None): _print("write class: "+str(clss)) anyElement = False lines.append(inc*indent+typelogger._signature_class(clss, assumed_globals, implicit_globals, assumed_typevars)) mb = inspect.getmembers(clss, lambda t: inspect.isclass(t) or type_util._check_as_func(t)) # todo: Care for overload-decorator for elem in mb: if elem[0] in clss.__dict__: el = clss.__dict__[elem[0]] if inspect.isfunction(el): lines.append('') _write_func(el, lines, inc+1, slf_or_clsm=True, assumed_globals=assumed_globals) anyElement = True elif inspect.isclass(el): lines.append('') if isinstance(el, TypeVar): _write_TypeVar(el, lines, inc+1) else: _write_class(el, lines, inc+1, assumed_globals, implicit_globals, assumed_typevars) anyElement = True elif inspect.ismethoddescriptor(el) and type(el) is staticmethod: lines.append('') _write_func(el.__func__, lines, inc+1, ['staticmethod'], assumed_globals=assumed_globals) anyElement = True elif isinstance(el, property): lines.append('') _write_property(el, lines, inc+1, assumed_globals=assumed_globals) anyElement = True # classmethods are not obtained via inspect.getmembers. # We have to look into __dict__ for that. for key in clss.__dict__: attr = getattr(clss, key) if util.is_classmethod(attr): lines.append('') _write_func(attr, lines, inc+1, ['classmethod'], True, assumed_globals) anyElement = True if not anyElement: lines.append((inc+1)*indent+'pass')
def create_environment(cog: 'Exec', ctx: DogbotContext) -> Dict[Any, Any]: async def upload(file_name: str) -> Message: """Shortcut to upload a file.""" with open(file_name, 'rb') as fp: return await ctx.send(file=discord.File(fp)) async def send(*args, **kwargs) -> Message: """Shortcut to send().""" return await ctx.send(*args, **kwargs) def better_dir(*args, **kwargs) -> List[str]: """dir(), but without magic methods.""" return [n for n in dir(*args, **kwargs) if not n.endswith('__') and not n.startswith('__')] T = TypeVar('T') def grabber(lst: List[T]) -> Callable[[int], T]: """Returns a function that, when called, grabs an item by ID from a list of objects with an ID.""" def _grabber_function(thing_id: int) -> T: return discord.utils.get(lst, id=thing_id) return _grabber_function env = { 'bot': ctx.bot, 'ctx': ctx, 'msg': ctx.message, 'guild': ctx.guild, 'channel': ctx.channel, 'me': ctx.message.author, 'cog': cog, # modules 'discord': discord, 'commands': commands, 'command': commands.command, 'group': commands.group, # utilities '_get': discord.utils.get, '_find': discord.utils.find, '_upload': upload, '_send': send, # grabbers '_g': grabber(ctx.bot.guilds), '_u': grabber(ctx.bot.users), '_c': grabber(list(ctx.bot.get_all_channels())), # last result '_': cog.last_result, '_p': cog.previous_code, 'dir': better_dir, } # add globals to environment env.update(globals()) return env
def deserialize_iterable_abstract_type(cls, cls_origin_type, data): abstract_type_map = { typing.Sequence: list, typing.List: list, typing.Set: set, typing.AbstractSet: set, typing.Mapping: Map, } deserialized_data = data cls_primitive_type = abstract_type_map[cls_origin_type] # Whereas on Python/typing < 3.5.2 type parameters are stored in # __parameters__ attribute, on Python/typing >= 3.5.2 __parameters__ # attribute is gone and __args__ comes instead. type_params = (cls.__args__ if hasattr(cls, '__args__') else cls.__parameters__) if len(type_params) == 1: elem_type, = type_params if isinstance(elem_type, typing.TypeVar): deserialized_data = cls_primitive_type(data) else: deserialized_data = cls_primitive_type( deserialize_meta(elem_type, d) for d in data ) elif len(type_params) == 2: # Key-value key_type, value_type = type_params assert not (isinstance(key_type, typing.TypeVar) or isinstance(value_type, typing.TypeVar)) if not isinstance(data, collections.Sequence): raise ValueError('map must be an array of item objects e.g. ' '[{"key": ..., "value": ...}, ...]') def parse_pair(pair): if not isinstance(pair, collections.Mapping): raise ValueError('map item must be a JSON object') try: key = pair['key'] value = pair['value'] except KeyError: raise ValueError('map item must consist of "key" and "value" ' 'fields e.g. {"key": ..., "value": ...}') return ( deserialize_meta(key_type, key), deserialize_meta(value_type, value), ) deserialized_data = cls_primitive_type(map(parse_pair, data)) return deserialized_data
def test_alias_many(self) -> None: pyi_txt = """ from typing import TypeVar _T = TypeVar('_T', bound=str) _EitherStr = Union[str, bytes] _MaybeStrings = List[Optional[_EitherStr]] SOME_GLOBAL: int def fun(error: _T) -> _T: ... def fun2(errors: _MaybeStrings) -> None: ... """ src_txt = """ "Docstring" from __future__ import print_function import sys SOME_GLOBAL: int = 0 def fun(error): return error @decorator def fun2(errors) -> None: for error in errors: if not error: continue print(error, file=sys.stderr) """ expected_txt = """ "Docstring" from __future__ import print_function import sys from typing import TypeVar SOME_GLOBAL: int = 0 _T = TypeVar('_T', bound=str) def fun(error: _T) -> _T: return error _EitherStr = Union[str, bytes] _MaybeStrings = List[Optional[_EitherStr]] @decorator def fun2(errors: _MaybeStrings) -> None: for error in errors: if not error: continue print(error, file=sys.stderr) """ self.assertReapply(pyi_txt, src_txt, expected_txt) self.assertReapplyVisible(pyi_txt, src_txt, expected_txt)