Python typing_extensions.Literal() Examples
The following are 30
code examples of typing_extensions.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_extensions
, or try the search function
.
Example #1
Source File: utils.py From typed-argument-parser with MIT License | 6 votes |
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
Example #2
Source File: images.py From aiodocker with Apache License 2.0 | 6 votes |
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[True] = False, encoding: str = None, ) -> AsyncIterator[Dict[str, Any]]: pass
Example #3
Source File: runner.py From pytest with MIT License | 6 votes |
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 )
Example #4
Source File: images.py From aiodocker with Apache License 2.0 | 6 votes |
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
Example #5
Source File: runner.py From pytest with MIT License | 6 votes |
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)
Example #6
Source File: argparsing.py From pytest with MIT License | 6 votes |
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)
Example #7
Source File: python.py From pytest with MIT License | 6 votes |
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))
Example #8
Source File: cloudpickle.py From ray with Apache License 2.0 | 6 votes |
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))
Example #9
Source File: test_core.py From dataclasses-jsonschema with MIT License | 6 votes |
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)
Example #10
Source File: asgi.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
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
Example #11
Source File: onscreentimer.py From ballistica with MIT License | 5 votes |
def getstarttime( self, timeformat: Literal[ba.TimeFormat.SECONDS] = ba.TimeFormat.SECONDS ) -> float: ...
Example #12
Source File: playerspaz.py From ballistica with MIT License | 5 votes |
def getplayer(self, playertype: Type[PlayerType], doraise: Literal[True]) -> PlayerType: ...
Example #13
Source File: _ba.py From ballistica with MIT License | 5 votes |
def getdelegate(self, type: Type[_T], doraise: Literal[False] = False) -> Optional[_T]: ...
Example #14
Source File: onscreentimer.py From ballistica with MIT License | 5 votes |
def getstarttime(self, timeformat: Literal[ba.TimeFormat.MILLISECONDS]) -> int: ...
Example #15
Source File: _actor.py From ballistica with MIT License | 5 votes |
def getactivity(self, doraise: Literal[False]) -> Optional[ba.Activity]: ...
Example #16
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 #17
Source File: _ba.py From ballistica with MIT License | 5 votes |
def getactivity(doraise: Literal[True] = True) -> ba.Activity: ...
Example #18
Source File: lazy.py From traffic with MIT License | 5 votes |
def lazy_evaluation( default: "Literal[None, False]" = False, idx_name: Optional[str] = None ) -> Callable[..., Callable[..., LazyTraffic]]: ...
Example #19
Source File: _ba.py From ballistica with MIT License | 5 votes |
def getinputdevice(name: str, unique_id: str, doraise: Literal[False]) -> Optional[ba.InputDevice]: ...
Example #20
Source File: images.py From aiodocker with Apache License 2.0 | 5 votes |
def push( self, name: str, *, auth: Union[MutableMapping, str, bytes] = None, tag: str = None, stream: Literal[False] = False, ) -> Dict[str, Any]: pass
Example #21
Source File: images.py From aiodocker with Apache License 2.0 | 5 votes |
def pull( self, from_image: str, *, auth: Optional[Union[MutableMapping, str, bytes]] = None, tag: str = None, repo: str = None, stream: Literal[True], ) -> AsyncIterator[Dict[str, Any]]: pass
Example #22
Source File: images.py From aiodocker with Apache License 2.0 | 5 votes |
def pull( self, from_image: str, *, auth: Optional[Union[MutableMapping, str, bytes]] = None, tag: str = None, repo: str = None, stream: Literal[False] = False, ) -> Dict[str, Any]: pass
Example #23
Source File: execs.py From aiodocker with Apache License 2.0 | 5 votes |
def start( self, *, timeout: aiohttp.ClientTimeout = None, detach: Literal[True], ) -> bytes: pass
Example #24
Source File: execs.py From aiodocker with Apache License 2.0 | 5 votes |
def start( self, *, timeout: aiohttp.ClientTimeout = None, detach: Literal[False], ) -> Stream: pass
Example #25
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 #26
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 #27
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 #28
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 #29
Source File: lazy.py From traffic with MIT License | 5 votes |
def lazy_evaluation( default: "Literal[True]", idx_name: Optional[str] = None ) -> Callable[..., Callable[..., "Traffic"]]: ...
Example #30
Source File: _ba.py From ballistica with MIT License | 5 votes |
def getsession(doraise: Literal[True] = True) -> ba.Session: ...