本文整理汇总了Python中typing_extensions.Literal方法的典型用法代码示例。如果您正苦于以下问题:Python typing_extensions.Literal方法的具体用法?Python typing_extensions.Literal怎么用?Python typing_extensions.Literal使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类typing_extensions
的用法示例。
在下文中一共展示了typing_extensions.Literal方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_url
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def _get_url(self, scope, default_scheme, host):
# type: (Dict[str, Any], Literal["ws", "http"], Optional[str]) -> str
"""
Extract URL from the ASGI scope, without also including the querystring.
"""
scheme = scope.get("scheme", default_scheme)
server = scope.get("server", None)
path = scope.get("root_path", "") + scope.get("path", "")
if host:
return "%s://%s%s" % (scheme, host, path)
if server is not None:
host, port = server
default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme]
if port != default_port:
return "%s://%s:%s%s" % (scheme, host, port, path)
return "%s://%s%s" % (scheme, host, path)
return path
示例2: get_literals
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def get_literals(literal: Literal, variable: str) -> Tuple[Callable[[str], Any], List[str]]:
"""Extracts the values from a Literal type and ensures that the values are all primitive types."""
literals = list(get_args(literal))
if not all(isinstance(literal, PRIMITIVES) for literal in literals):
raise ValueError(
f'The type for variable "{variable}" contains a literal'
f'of a non-primitive type e.g. (str, int, float, bool).\n'
f'Currently only primitive-typed literals are supported.'
)
str_to_literal = {str(literal): literal for literal in literals}
if len(literals) != len(str_to_literal):
raise ValueError('All literals must have unique string representations')
def var_type(arg: str) -> Any:
return str_to_literal[arg]
return var_type, literals
示例3: setmulti2
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def setmulti2(
self,
valtypes: "Mapping[str, Literal['params', 'funcargs']]",
argnames: typing.Sequence[str],
valset: Iterable[object],
id: str,
marks: Iterable[Union[Mark, MarkDecorator]],
scopenum: int,
param_index: int,
) -> None:
for arg, val in zip(argnames, valset):
self._checkargnotcontained(arg)
valtype_for_arg = valtypes[arg]
if valtype_for_arg == "params":
self.params[arg] = val
elif valtype_for_arg == "funcargs":
self.funcargs[arg] = val
else: # pragma: no cover
assert False, "Unhandled valtype for arg: {}".format(valtype_for_arg)
self.indices[arg] = param_index
self._arg2scopenum[arg] = scopenum
self._idlist.append(id)
self.marks.extend(normalize_mark_list(marks))
示例4: _update_current_test_var
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def _update_current_test_var(
item: Item, when: Optional["Literal['setup', 'call', 'teardown']"]
) -> None:
"""
Update :envvar:`PYTEST_CURRENT_TEST` to reflect the current item and stage.
If ``when`` is None, delete ``PYTEST_CURRENT_TEST`` from the environment.
"""
var_name = "PYTEST_CURRENT_TEST"
if when:
value = "{} ({})".format(item.nodeid, when)
# don't allow null bytes on environment variables (see #2644, #2957)
value = value.replace("\x00", "(null)")
os.environ[var_name] = value
else:
os.environ.pop(var_name)
示例5: call_runtest_hook
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def call_runtest_hook(
item: Item, when: "Literal['setup', 'call', 'teardown']", **kwds
) -> "CallInfo[None]":
if when == "setup":
ihook = item.ihook.pytest_runtest_setup # type: Callable[..., None]
elif when == "call":
ihook = item.ihook.pytest_runtest_call
elif when == "teardown":
ihook = item.ihook.pytest_runtest_teardown
else:
assert False, "Unhandled runtest hook case: {}".format(when)
reraise = (Exit,) # type: Tuple[Type[BaseException], ...]
if not item.config.getoption("usepdb", False):
reraise += (KeyboardInterrupt,)
return CallInfo.from_call(
lambda: ihook(item=item, **kwds), when=when, reraise=reraise
)
示例6: addini
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def addini(
self,
name: str,
help: str,
type: Optional["Literal['pathlist', 'args', 'linelist', 'bool']"] = None,
default=None,
) -> None:
""" register an ini-file option.
:name: name of the ini-variable
:type: type of the variable, can be ``pathlist``, ``args``, ``linelist``
or ``bool``.
:default: default value if no ini-file option exists but is queried.
The value of ini-variables can be retrieved via a call to
:py:func:`config.getini(name) <_pytest.config.Config.getini>`.
"""
assert type in (None, "pathlist", "args", "linelist", "bool")
self._inidict[name] = (help, type, default)
self._ininames.append(name)
示例7: test_literal_types
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def test_literal_types():
@dataclass
class ImageMeta(JsonSchemaMixin):
"""Image metadata"""
bits_per_pixel: Literal[8, 16, 24, "true-color", None]
expected_schema = {
'type': 'object',
'description': 'Image metadata',
'properties': {
'bits_per_pixel': {'enum': [8, 16, 24, 'true-color', None]}
},
'required': ['bits_per_pixel']
}
assert ImageMeta.json_schema() == compose_schema(expected_schema)
assert ImageMeta(bits_per_pixel=16).to_dict() == {"bits_per_pixel": 16}
assert ImageMeta.from_dict({"bits_per_pixel": 16}) == ImageMeta(bits_per_pixel=16)
示例8: build
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def build(
self,
*,
remote: str = None,
fileobj: BinaryIO = None,
path_dockerfile: str = None,
tag: str = None,
quiet: bool = False,
nocache: bool = False,
buildargs: Mapping = None,
pull: bool = False,
rm: bool = True,
forcerm: bool = False,
labels: Mapping = None,
stream: Literal[False] = False,
encoding: str = None,
) -> Dict[str, Any]:
pass
示例9: _is_parametrized_type_hint
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def _is_parametrized_type_hint(obj):
# This is very cheap but might generate false positives.
# general typing Constructs
is_typing = getattr(obj, '__origin__', None) is not None
# typing_extensions.Literal
is_litteral = getattr(obj, '__values__', None) is not None
# typing_extensions.Final
is_final = getattr(obj, '__type__', None) is not None
# typing.Union/Tuple for old Python 3.5
is_union = getattr(obj, '__union_params__', None) is not None
is_tuple = getattr(obj, '__tuple_params__', None) is not None
is_callable = (
getattr(obj, '__result__', None) is not None and
getattr(obj, '__args__', None) is not None
)
return any((is_typing, is_litteral, is_final, is_union, is_tuple,
is_callable))
示例10: test_get_literals_string
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def test_get_literals_string(self) -> None:
literal_f, shapes = get_literals(Literal['square', 'triangle', 'circle'], 'shape')
self.assertEqual(shapes, ['square', 'triangle', 'circle'])
self.assertEqual(literal_f('square'), 'square')
self.assertEqual(literal_f('triangle'), 'triangle')
self.assertEqual(literal_f('circle'), 'circle')
with self.assertRaises(KeyError):
literal_f('tuba')
示例11: test_get_literals_primitives
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def test_get_literals_primitives(self) -> None:
literals = [True, 'one', 2, 3.14]
literal_f, prims = get_literals(Literal[True, 'one', 2, 3.14], 'number')
self.assertEqual(prims, literals)
self.assertEqual([literal_f(str(p)) for p in prims], literals)
with self.assertRaises(KeyError):
literal_f(3)
示例12: test_get_literals_uniqueness
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def test_get_literals_uniqueness(self) -> None:
with self.assertRaises(ValueError):
get_literals(Literal['two', 2, '2'], 'number')
示例13: test_get_literals_empty
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def test_get_literals_empty(self) -> None:
literal_f, prims = get_literals(Literal, 'hi')
self.assertEqual(prims, [])
with self.assertRaises(KeyError):
literal_f(None)
示例14: __getitem__
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def __getitem__(cls, values):
if not isinstance(values, tuple):
values = (values,)
return type('Literal_', (Literal,), dict(__args__=values))
示例15: REQ
# 需要导入模块: import typing_extensions [as 别名]
# 或者: from typing_extensions import Literal [as 别名]
def REQ(
whence: Optional[str] = ...,
*,
default: ResultT = ...,
argument_type: Literal["body"],
intentionally_undocumented: bool = ...,
documentation_pending: bool = ...,
aliases: Sequence[str] = ...,
path_only: bool = ...
) -> ResultT:
...
# Implementation