當前位置: 首頁>>代碼示例>>Python>>正文


Python typing_extensions.Literal方法代碼示例

本文整理匯總了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 
開發者ID:getsentry,項目名稱:sentry-python,代碼行數:22,代碼來源:asgi.py

示例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 
開發者ID:swansonk14,項目名稱:typed-argument-parser,代碼行數:22,代碼來源:utils.py

示例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)) 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:25,代碼來源:python.py

示例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) 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:18,代碼來源:runner.py

示例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
    ) 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:19,代碼來源:runner.py

示例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) 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:22,代碼來源:argparsing.py

示例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) 
開發者ID:s-knibbs,項目名稱:dataclasses-jsonschema,代碼行數:20,代碼來源:test_core.py

示例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 
開發者ID:aio-libs,項目名稱:aiodocker,代碼行數:20,代碼來源:images.py

示例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)) 
開發者ID:ray-project,項目名稱:ray,代碼行數:22,代碼來源:cloudpickle.py

示例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') 
開發者ID:swansonk14,項目名稱:typed-argument-parser,代碼行數:10,代碼來源:test_utils.py

示例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) 
開發者ID:swansonk14,項目名稱:typed-argument-parser,代碼行數:9,代碼來源:test_utils.py

示例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') 
開發者ID:swansonk14,項目名稱:typed-argument-parser,代碼行數:5,代碼來源:test_utils.py

示例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) 
開發者ID:swansonk14,項目名稱:typed-argument-parser,代碼行數:7,代碼來源:test_utils.py

示例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)) 
開發者ID:theislab,項目名稱:scanpy,代碼行數:6,代碼來源:_compat.py

示例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 
開發者ID:zulip,項目名稱:zulip,代碼行數:15,代碼來源:request.py


注:本文中的typing_extensions.Literal方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。