Python typing.Optional() Examples

The following are 30 code examples of typing.Optional(). 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: filters.py    From mutatest with MIT License 7 votes vote down vote up
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() 
Example #2
Source File: args_format.py    From clikit with MIT License 6 votes vote down vote up
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 
Example #3
Source File: abstract_option.py    From clikit with MIT License 6 votes vote down vote up
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.") 
Example #4
Source File: output.py    From clikit with MIT License 6 votes vote down vote up
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 = [] 
Example #5
Source File: output.py    From clikit with MIT License 6 votes vote down vote up
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)) 
Example #6
Source File: command.py    From clikit with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: section_output.py    From clikit with MIT License 6 votes vote down vote up
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)
        ) 
Example #8
Source File: cli.py    From mutatest with MIT License 6 votes vote down vote up
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."
    ) 
Example #9
Source File: string.py    From clikit with MIT License 6 votes vote down vote up
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)) 
Example #10
Source File: input_stream.py    From clikit with MIT License 5 votes vote down vote up
def read_line(self, length=None):  # type: (Optional[int]) -> str
        """
        Reads a line from the stream.
        """
        raise NotImplementedError() 
Example #11
Source File: string.py    From clikit with MIT License 5 votes vote down vote up
def get_string_length(
    string, formatter=None
):  # type: (str, Optional[Formatter]) -> int
    if formatter is not None:
        string = formatter.remove_format(string)

    return len(string) 
Example #12
Source File: output.py    From clikit with MIT License 5 votes vote down vote up
def write_line(self, string, flags=None):  # type: (str, Optional[int]) -> None
        """
        Writes a line of text to the output stream.

        The string is formatted before it is written to the output stream.
        """
        self.write(string, flags=flags, new_line=True) 
Example #13
Source File: section_output.py    From clikit with MIT License 5 votes vote down vote up
def write(
        self, string, flags=None, new_line=False
    ):  # type: (str, Optional[int], bool) -> None
        if not self.supports_ansi() and not self._formatter.force_ansi():
            return super(SectionOutput, self).write(string, flags=flags)

        erased_content = self._pop_stream_content_until_current_section()

        self.add_content(string)

        super(SectionOutput, self).write(string, new_line=True)
        super(SectionOutput, self).write(erased_content) 
Example #14
Source File: string.py    From clikit with MIT License 5 votes vote down vote up
def parse_string(value, nullable=True):  # type: (Any, bool) -> Optional[str]
    if nullable and (value is None or value == "null"):
        return

    if value is None:
        return "null"

    if isinstance(value, bool):
        return str(value).lower()

    return str(value) 
Example #15
Source File: string.py    From clikit with MIT License 5 votes vote down vote up
def parse_int(value, nullable=True):  # type: (Any, bool) -> Optional[int]
    if nullable and (value is None or value == "null"):
        return

    try:
        return int(value)
    except ValueError:
        raise ValueError('The value "{}" cannot be parsed as integer.'.format(value)) 
Example #16
Source File: string.py    From clikit with MIT License 5 votes vote down vote up
def get_max_line_length(
    string, formatter=None
):  # type: (str, Optional[Formatter]) -> int
    if formatter is not None:
        string = formatter.remove_format(string)

    max_length = 0
    words = re.split("\n", string)

    for word in words:
        max_length = max(max_length, get_string_length(word))

    return max_length 
Example #17
Source File: command_config.py    From clikit with MIT License 5 votes vote down vote up
def __init__(self, name=None):  # type: (Optional[str]) -> None
        super(CommandConfig, self).__init__()

        self._name = name
        self._aliases = []
        self._description = ""
        self._help = None
        self._enabled = True
        self._hidden = False
        self._process_title = None
        self._default = None
        self._anonymous = None
        self._sub_command_configs = []  # type: List[CommandConfig]

        self._parent_config = None  # type: Optional[CommandConfig] 
Example #18
Source File: filters.py    From mutatest with MIT License 5 votes vote down vote up
def __init__(self, coverage_file: Union[str, Path] = Path(".coverage")) -> None:
        """Initialize the filter.

        Args:
            coverage_file: an optional coverage file, a default ".coverage" is used.
        """
        self._coverage_file = Path(coverage_file)
        self._coverage_data: Optional[CoverageData] = None 
Example #19
Source File: input.py    From clikit with MIT License 5 votes vote down vote up
def read_line(
        self, length=None, default=None
    ):  # type: (Optional[int], Optional[str]) -> str
        """
        Reads a line from the input stream.

        :raises: IOException
        """
        if not self._interactive:
            return default

        return self._stream.read_line(length=length) 
Example #20
Source File: command.py    From clikit with MIT License 5 votes vote down vote up
def _do_handle(self, args, io):  # type: (Args, IO) -> Optional[int]
        if self._dispatcher and self._dispatcher.has_listeners(PRE_HANDLE):
            event = PreHandleEvent(args, io, self)
            self._dispatcher.dispatch(PRE_HANDLE, event)

            if event.is_handled():
                return event.status_code

        handler = self._config.handler
        handler_method = self._config.handler_method

        return getattr(handler, handler_method)(args, io, self) 
Example #21
Source File: command.py    From clikit with MIT License 5 votes vote down vote up
def base_format(self):  # type: () -> Optional[ArgsFormat]
        if self._parent_command:
            return self._parent_command.args_format

        if self._application:
            return self._application.global_args_format

        return 
Example #22
Source File: command.py    From clikit with MIT License 5 votes vote down vote up
def parse(self, args, lenient=None):  # type: (RawArgs, Optional[bool]) -> Args
        if lenient is None:
            lenient = self._config.is_lenient_args_parsing_enabled()

        return self._config.args_parser.parse(args, self._args_format, lenient) 
Example #23
Source File: command_config.py    From clikit with MIT License 5 votes vote down vote up
def build_args_format(
        self, base_format=None
    ):  # type: (Optional[ArgsFormat]) -> ArgsFormat
        builder = ArgsFormatBuilder(base_format)

        if not self._anonymous:
            builder.add_command_name(CommandName(self.name, self.aliases))

        builder.add_options(*self.options.values())
        builder.add_arguments(*self.arguments.values())

        return builder.format 
Example #24
Source File: command_config.py    From clikit with MIT License 5 votes vote down vote up
def parent_config(self):  # type: () -> Optional[CommandConfig]
        return self._parent_config 
Example #25
Source File: command_config.py    From clikit with MIT License 5 votes vote down vote up
def set_process_title(
        self, process_title
    ):  # type: (Optional[str]) -> CommandConfig
        self._process_title = process_title

        return self 
Example #26
Source File: command_config.py    From clikit with MIT License 5 votes vote down vote up
def process_title(self):  # type: () -> Optional[str]
        return self._process_title 
Example #27
Source File: command_config.py    From clikit with MIT License 5 votes vote down vote up
def set_help(self, help):  # type: (Optional[str]) -> CommandConfig
        self._help = help

        return self 
Example #28
Source File: command_config.py    From clikit with MIT License 5 votes vote down vote up
def help(self):  # type: () -> Optional[str]
        return self._help 
Example #29
Source File: command_config.py    From clikit with MIT License 5 votes vote down vote up
def name(self):  # type: () -> Optional[str]
        return self._name 
Example #30
Source File: progress_indicator.py    From clikit with MIT License 5 votes vote down vote up
def __init__(
        self, io, fmt=None, interval=100, values=None
    ):  # type: (Union[IO, Output], Optional[str], int, Optional[List[str]]) -> None
        if isinstance(io, IO):
            io = io.error_output

        self._io = io

        if fmt is None:
            fmt = self._determine_best_format()

        self._fmt = fmt

        if values is None:
            values = ["-", "\\", "|", "/"]

        if len(values) < 2:
            raise ValueError(
                "The progress indicator must have at least 2 indicator value characters."
            )

        self._interval = interval
        self._values = values

        self._message = None
        self._update_time = None
        self._started = False
        self._current = 0

        self._auto_running = None
        self._auto_thread = None

        self._start_time = None
        self._last_message_length = 0