本文整理匯總了Python中typing.Optional方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.Optional方法的具體用法?Python typing.Optional怎麽用?Python typing.Optional使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類typing
的用法示例。
在下文中一共展示了typing.Optional方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def __init__(
self, long_name, short_name=None, aliases=None, flags=0, description=None
): # type: (str, Optional[str], Optional[List[str]], int, Optional[str]) -> None
super(CommandOption, self).__init__(long_name, short_name, flags, description)
if aliases is None:
aliases = []
self._long_aliases = []
self._short_aliases = []
for alias in aliases:
alias = self._remove_dash_prefix(alias)
if len(alias) == 1:
self._validate_short_alias(alias)
self._short_aliases.append(alias)
else:
self._validate_long_alias(alias)
self._long_aliases.append(alias)
示例2: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def __init__(self, codes: Optional[Iterable[str]] = None):
"""Initialize the filter.
Args:
codes: An optional iterable of two-letter category codes for filtering.
Optional to set at initialization of the class, can be set through properties.
The codes property must be set prior to filtering.
Only codes that are valid categories are added, others are discarded.
Make sure you set appropriately as an iterable for single string values e.g.,
``codes=("bn",)``; otherwise, the codes property will set as empty.
"""
# managed by class properties, no direct setters
self._valid_categories = CATEGORIES # defined in transformers.py
self._codes: Set[str] = set()
# initialize through properties
self.codes = set(codes) if codes else set()
示例3: get_src_location
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def get_src_location(src_loc: Optional[Path] = None) -> Path:
"""Find packages is used if the ``src_loc`` is not set
Args:
src_loc: current source location, defaults to None
Returns:
Path to the source location
Raises:
FileNoeFoundError: if the source location doesn't exist.
"""
if not src_loc:
find_pkgs = find_packages()
if find_pkgs:
src_loc = Path(find_pkgs[0])
return src_loc
else:
if src_loc.exists():
return src_loc
raise FileNotFoundError(
"No source directory specified or automatically detected. "
"Use --src or --help to see options."
)
示例4: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def __init__(
self, long_name, short_name=None, flags=0, description=None
): # type: (str, Optional[str], int, Optional[str]) -> None
long_name = self._remove_double_dash_prefix(long_name)
short_name = self._remove_dash_prefix(short_name)
self._validate_flags(flags)
self._validate_long_name(long_name)
self._validate_short_name(short_name, flags)
self._long_name = long_name
self._short_name = short_name
self._description = description
flags = self._add_default_flags(flags)
self._flags = flags
示例5: _validate_short_name
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def _validate_short_name(
self, short_name, flags
): # type: (Optional[str], int) -> None
if short_name is None:
if flags & self.PREFER_SHORT_NAME:
raise ValueError(
"The short option name must be given if the option flag PREFER_SHORT_NAME is selected."
)
return
if not isinstance(short_name, basestring):
raise ValueError(
"The short option name must be a string. Got: {}".format(
type(short_name)
)
)
if not short_name:
raise ValueError("The short option name must not be empty.")
if not re.match(r"^[a-zA-Z]$", short_name):
raise ValueError("The short option name must be exactly one letter.")
示例6: _create_builder_for_elements
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def _create_builder_for_elements(
self, elements, base_format=None
): # type: (List[Any], Optional[ArgsFormat]) -> ArgsFormatBuilder
from .args_format_builder import ArgsFormatBuilder
builder = ArgsFormatBuilder(base_format)
for element in elements:
if isinstance(element, CommandName):
builder.add_command_name(element)
elif isinstance(element, CommandOption):
builder.add_command_option(element)
elif isinstance(element, Option):
builder.add_option(element)
elif isinstance(element, Argument):
builder.add_argument(element)
return builder
示例7: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def __init__(
self, config, application=None, parent_command=None
): # type: (CommandConfig, Optional[Application], Optional[Command]) -> None
from .command_collection import CommandCollection
if not config.name:
raise RuntimeError("The name of the command config must be set.")
self._name = config.name
self._short_name = None
self._aliases = config.aliases
self._config = config
self._application = application
self._parent_command = parent_command
self._sub_commands = CommandCollection()
self._named_sub_commands = CommandCollection()
self._default_sub_commands = CommandCollection()
self._args_format = config.build_args_format(self.base_format)
self._dispatcher = application.config.dispatcher if application else None
for sub_config in config.sub_command_configs:
self.add_sub_command(sub_config)
示例8: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def __init__(
self, stream, formatter=None
): # type: (OutputStream, Optional[Formatter]) -> None
self._stream = stream
if formatter is None:
formatter = NullFormatter()
self._formatter = formatter
self._quiet = False
self._format_output = (
self._stream.supports_ansi()
and not formatter.disable_ansi()
or formatter.force_ansi()
)
self._verbosity = 0
self._section_outputs = []
示例9: write
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def write(
self, string, flags=None, new_line=False
): # type: (str, Optional[int], bool) -> None
"""
Writes a string to the output stream.
The string is formatted before it is written to the output stream.
"""
if self._may_write(flags):
if self._format_output:
formatted = self.format(string)
else:
formatted = self.remove_format(string)
if new_line:
formatted += "\n"
self._stream.write(to_str(formatted))
示例10: clear
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def clear(self, lines=None): # type: (Optional[int]) -> None
if (
not self._content
or not self.supports_ansi()
and not self._formatter.force_ansi()
):
return
if lines:
# Multiply lines by 2 to cater for each new line added between content
del self._content[-(lines * 2) :]
else:
lines = self._lines
self._content = []
self._lines -= lines
super(SectionOutput, self).write(
self._pop_stream_content_until_current_section(lines)
)
示例11: parse_boolean
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def parse_boolean(value, nullable=True): # type: (Any, bool) -> Optional[bool]
if nullable and (value is None or value == "null"):
return
if isinstance(value, bool):
return value
if isinstance(value, int):
value = str(value)
if isinstance(value, basestring):
if not value:
return False
if value in {"false", "0", "no", "off"}:
return False
if value in {"true", "1", "yes", "on"}:
return True
raise ValueError('The value "{}" cannot be parsed as boolean.'.format(value))
示例12: end_lineno
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def end_lineno(self) -> Optional[int]:
"""End line no: Python 3.8 will have this defined, in Python 3.7 it will be None."""
eline: Optional[int] = getattr(self.node, "end_lineno", None)
return eline
示例13: end_col_offset
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def end_col_offset(self) -> Optional[int]:
"""End col offset: Python 3.8 will have this defined, in Python 3.7 it will be None."""
ecol: Optional[int] = getattr(self.node, "end_col_offset", None)
return ecol
####################################################################################################
# MUTATE AST Definitions
# Includes MutateBase and Mixins for 3.7 and 3.8 AST support
# MutateAST is constructed from Base + Mixins depending on sys.version_info
####################################################################################################
示例14: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def __init__(
self,
target_idx: Optional[LocIndex] = None,
mutation: Optional[Any] = None,
readonly: bool = False,
src_file: Optional[Union[Path, str]] = None,
) -> None:
"""Create the AST node transformer for mutations.
If readonly is set to True then no transformations are applied;
however, the locs attribute is updated with the locations of nodes that could
be transformed. This allows the class to function both as an inspection method
and as a mutation transformer.
Note that different nodes handle the ``LocIndex`` differently based on the context. For
example, ``visit_BinOp`` uses direct AST types, while ``visit_NameConstant`` uses values,
and ``visit_AugAssign`` uses custom strings in a dictionary mapping.
All ``visit_`` methods take the ``node`` as an argument and rely on the class properties.
This MutateBase class is designed to be implemented with the appropriate Mixin Class
for supporting either Python 3.7 or Python 3.8 ASTs. If the base class is used
directly certain operations - like ``visit_If`` and ``visit_NameConstant`` will not
work as intended..
Args:
target_idx: Location index for the mutatest in the AST
mutation: the mutatest to apply, may be a type or a value
readonly: flag for read-only operations, used to visit nodes instead of transform
src_file: Source file name, used for logging purposes
"""
self.locs: Set[LocIndex] = set()
# managed via @property
self._target_idx = target_idx
self._mutation = mutation
self._readonly = readonly
self._src_file = src_file
示例15: mutation
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Optional [as 別名]
def mutation(self) -> Optional[Any]:
"""The mutation to apply, may be a type or a value"""
return self._mutation