Python typing.Literal() Examples
The following are 30
code examples of typing.Literal().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
typing
, or try the search function
.
Example #1
Source File: absltest.py From abseil-py with Apache License 2.0 | 6 votes |
def open_bytes(self, mode='rb'): # type: (Text) -> ContextManager[BinaryIO] """Return a context manager for opening the file in binary mode. Args: mode: The mode to open the file in. The "b" mode is implicit if not already present. It must not have the "t" flag. Returns: Context manager that yields an open file. Raises: ValueError: if invalid inputs are provided. """ if 't' in mode: raise ValueError('Invalid mode {!r}: "t" flag not allowed when opening ' 'file in binary mode'.format(mode)) if 'b' not in mode: mode += 'b' cm = self._open(mode, encoding=None, errors=None) # type: ContextManager[BinaryIO] return cm # TODO(b/123775699): Once pytype supports typing.Literal, use overload and # Literal to express more precise return types and remove the type comments in # open_text and open_bytes.
Example #2
Source File: defopt.py From defopt with MIT License | 5 votes |
def _ti_get_origin(tp): import typing_inspect as ti if type(tp) is type(Literal): # Py<=3.6. return Literal origin = ti.get_origin(tp) return { # Py<=3.6. typing.List: list, typing.Iterable: collections.abc.Iterable, typing.Sequence: collections.abc.Sequence, typing.Tuple: tuple, }.get(origin, origin)
Example #3
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_instance_with_optional_literal_and_not_matching_type(): from typing import Literal assert not is_instance("C", Optional[Literal["A", "B"]])
Example #4
Source File: test_literal.py From dacite with MIT License | 5 votes |
def test_from_dict_with_literal(): from typing import Literal @dataclass class X: l: Literal["A", "B"] result = from_dict(X, {"l": "A"}) assert result == X(l="A")
Example #5
Source File: test_literal.py From dacite with MIT License | 5 votes |
def test_from_dict_with_literal_and_wrong_value(): from typing import Literal @dataclass class X: l: Literal["A", "B"] with pytest.raises(WrongTypeError) as exception_info: from_dict(X, {"l": "C"})
Example #6
Source File: test_literal.py From dacite with MIT License | 5 votes |
def test_from_dict_with_optional_literal_and_none(): from typing import Literal @dataclass class X: l: Optional[Literal["A", "B"]] result = from_dict(X, {"l": None}) assert result == X(l=None)
Example #7
Source File: test_literal.py From dacite with MIT License | 5 votes |
def test_from_dict_with_optional_literal_and_not_none(): from typing import Literal @dataclass class X: l: Optional[Literal["A", "B"]] result = from_dict(X, {"l": "A"}) assert result == X(l="A")
Example #8
Source File: choices.py From defopt with MIT License | 5 votes |
def choose_literal(arg: Literal["foo", "bar"], *, opt: Literal["baz", "quu"] = None): """ Example function with `typing.Literal` arguments. :param arg: Choice to display :param opt: Optional choice to display """ print(arg) if opt: print(opt)
Example #9
Source File: defopt.py From defopt with MIT License | 5 votes |
def _ti_get_args(tp): import typing_inspect as ti if type(tp) is type(Literal): # Py<=3.6. return tp.__values__ return ti.get_args(tp, evaluate=True) # evaluate=True default on Py>=3.7.
Example #10
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_instance_with_optional_literal_and_matching_type(): from typing import Literal assert is_instance("A", Optional[Literal["A", "B"]])
Example #11
Source File: defopt.py From defopt with MIT License | 5 votes |
def _get_parser(type_, parsers): try: parser = functools.partial(parsers[type_]) except KeyError: if (type_ in [str, int, float] or isinstance(type_, type) and issubclass(type_, PurePath)): parser = functools.partial(type_) elif type_ == bool: parser = functools.partial(_parse_bool) elif type_ == slice: parser = functools.partial(_parse_slice) elif type_ == list: raise ValueError('unable to parse list (try list[type])') elif isinstance(type_, type) and issubclass(type_, Enum): parser = _make_enum_parser(type_) elif _is_constructible_from_str(type_): parser = functools.partial(type_) elif _ti_get_origin(type_) is Union: parser = _make_union_parser( type_, [_get_parser(arg, parsers) for arg in _ti_get_args(type_)]) elif _ti_get_origin(type_) is Literal: # Py>=3.7. parser = _make_literal_parser( type_, [_get_parser(type(arg), parsers) for arg in _ti_get_args(type_)]) else: raise Exception('no parser found for type {}'.format( # typing types have no __name__. getattr(type_, '__name__', repr(type_)))) # Set the name that the user expects to see in error messages (we always # return a temporary partial object so it's safe to set its __name__). # Unions and Literals don't have a __name__, but their str is fine. parser.__name__ = getattr(type_, '__name__', str(type_)) return parser
Example #12
Source File: _typing.py From pytablewriter with MIT License | 5 votes |
def __instancecheck__(self, obj): raise TypeError("Literal cannot be used with isinstance().")
Example #13
Source File: _typing.py From pytablewriter with MIT License | 5 votes |
def __subclasscheck__(self, cls): raise TypeError("Literal cannot be used with issubclass().")
Example #14
Source File: _typing.py From pytablewriter with MIT License | 5 votes |
def __eq__(self, other): if not isinstance(other, Literal): return NotImplemented if self.__values__ is not None: return self.__values__ == other.__values__ return self is other
Example #15
Source File: typing.py From pydantic with MIT License | 5 votes |
def is_literal_type(type_: Type[Any]) -> bool: return Literal is not None and getattr(type_, '__origin__', None) is Literal
Example #16
Source File: typing.py From pydantic with MIT License | 5 votes |
def is_literal_type(type_: Type[Any]) -> bool: return Literal is not None and hasattr(type_, '__values__') and type_ == Literal[type_.__values__]
Example #17
Source File: typing.py From pydantic with MIT License | 5 votes |
def all_literal_values(type_: Type[Any]) -> Tuple[Any, ...]: """ This method is used to retrieve all Literal values as Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586) e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]` """ if not is_literal_type(type_): return (type_,) values = literal_values(type_) return tuple(x for value in values for x in all_literal_values(value))
Example #18
Source File: http_common.py From py-ipfs-http-client with MIT License | 5 votes |
def request( self, path: str, args: ty.Sequence[str] = [], *, opts: ty.Mapping[str, str] = {}, decoder: str = "none", stream: bool = False, offline: bool = False, return_result: ty.Literal[False], auth: auth_t = None, cookies: cookies_t = None, data: reqdata_sync_t = None, headers: headers_t = None, timeout: timeout_t = None ) -> None: ...
Example #19
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_instance_with_literal_and_not_matching_type(): from typing import Literal assert not is_instance("C", Literal["A", "B"])
Example #20
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_instance_with_literal_and_matching_type(): from typing import Literal assert is_instance("A", Literal["A", "B"])
Example #21
Source File: test_types.py From dacite with MIT License | 5 votes |
def test_is_literal_with_literal(): from typing import Literal assert is_literal(Literal["A", "B"])
Example #22
Source File: __init__.py From anndata with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __getitem__(cls, values): if not isinstance(values, tuple): values = (values,) return type("Literal_", (Literal,), dict(__args__=values))
Example #23
Source File: test_type_annotations.py From pyflakes with MIT License | 5 votes |
def test_literal_union_type_typing(self): self.flakes(""" from typing import Literal def f(x: Literal['some string', 'foo bar']) -> None: return None """)
Example #24
Source File: test_type_annotations.py From pyflakes with MIT License | 5 votes |
def test_literal_type_some_other_module(self): """err on the side of false-negatives for types named Literal""" self.flakes(""" from my_module import compat from my_module.compat import Literal def f(x: compat.Literal['some string']) -> None: return None def g(x: Literal['some string']) -> None: return None """)
Example #25
Source File: test_type_annotations.py From pyflakes with MIT License | 5 votes |
def test_literal_type_typing_extensions(self): self.flakes(""" from typing_extensions import Literal def f(x: Literal['some string']) -> None: return None """)
Example #26
Source File: test_type_annotations.py From pyflakes with MIT License | 5 votes |
def test_literal_type_typing(self): self.flakes(""" from typing import Literal def f(x: Literal['some string']) -> None: return None """)
Example #27
Source File: io.py From CharGer with GNU General Public License v3.0 | 5 votes |
def read_tsv( path: Path, as_dict: Literal[True], columns: List[str], **kwargs ) -> Generator[Dict[str, str], None, None]: ...
Example #28
Source File: io.py From CharGer with GNU General Public License v3.0 | 5 votes |
def read_tsv( path: Path, as_dict: Literal[False], **kwargs ) -> Generator[List[str], None, None]: ...
Example #29
Source File: _compat.py From scanpy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __getitem__(cls, values): if not isinstance(values, tuple): values = (values,) return type('Literal_', (Literal,), dict(__args__=values))
Example #30
Source File: encoding.py From py-ipfs-http-client with MIT License | 5 votes |
def get_encoding(name: ty.Literal["none"]) -> Dummy: ...