Python typing.Match() Examples

The following are 30 code examples of typing.Match(). 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: client.py    From nats-python with MIT License 6 votes vote down vote up
def _handle_message(self, result: Match[bytes]) -> None:
        message_data = result.groupdict()

        message_payload_size = int(message_data["size"])
        message_payload = self._readline(size=message_payload_size)
        message_payload = self._strip(message_payload)

        message = NATSMessage(
            sid=int(message_data["sid"].decode()),
            subject=message_data["subject"].decode(),
            reply=message_data["reply"].decode() if message_data["reply"] else "",
            payload=message_payload,
        )

        sub = self._subs[message.sid]
        sub.received_messages += 1

        if sub.is_wasted():
            self._subs.pop(sub.sid)

        sub.callback(message) 
Example #2
Source File: test_typing.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_any_is_subclass(self):
        # Any should be considered a subclass of everything.
        assert issubclass(Any, Any)
        assert issubclass(Any, typing.List)
        assert issubclass(Any, typing.List[int])
        assert issubclass(Any, typing.List[T])
        assert issubclass(Any, typing.Mapping)
        assert issubclass(Any, typing.Mapping[str, int])
        assert issubclass(Any, typing.Mapping[KT, VT])
        assert issubclass(Any, Generic)
        assert issubclass(Any, Generic[T])
        assert issubclass(Any, Generic[KT, VT])
        assert issubclass(Any, AnyStr)
        assert issubclass(Any, Union)
        assert issubclass(Any, Union[int, str])
        assert issubclass(Any, typing.Match)
        assert issubclass(Any, typing.Match[str])
        # These expressions must simply not fail.
        typing.Match[Any]
        typing.Pattern[Any]
        typing.IO[Any] 
Example #3
Source File: test_typing.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_basics(self):
        pat = re.compile('[a-z]+', re.I)
        assert issubclass(pat.__class__, Pattern)
        assert issubclass(type(pat), Pattern)
        assert issubclass(type(pat), Pattern[str])

        mat = pat.search('12345abcde.....')
        assert issubclass(mat.__class__, Match)
        assert issubclass(mat.__class__, Match[str])
        assert issubclass(mat.__class__, Match[bytes])  # Sad but true.
        assert issubclass(type(mat), Match)
        assert issubclass(type(mat), Match[str])

        p = Pattern[Union[str, bytes]]
        assert issubclass(Pattern[str], Pattern)
        assert issubclass(Pattern[str], p)

        m = Match[Union[bytes, str]]
        assert issubclass(Match[bytes], Match)
        assert issubclass(Match[bytes], m) 
Example #4
Source File: test_typing.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_errors(self):
        with self.assertRaises(TypeError):
            # Doesn't fit AnyStr.
            Pattern[int]
        with self.assertRaises(TypeError):
            # Can't change type vars?
            Match[T]
        m = Match[Union[str, bytes]]
        with self.assertRaises(TypeError):
            # Too complicated?
            m[str]
        with self.assertRaises(TypeError):
            # We don't support isinstance().
            isinstance(42, Pattern)
        with self.assertRaises(TypeError):
            # We don't support isinstance().
            isinstance(42, Pattern[str]) 
Example #5
Source File: printer.py    From pywayland with Apache License 2.0 6 votes vote down vote up
def _doc_class_replace(self, match: Match) -> str:
        """Build the sphinx doc class import

        :param match:
            The regex match for the given interface class.
        :returns:
            The string corresponding to the sphinx formatted class.
        """
        interface_name = match.group("interface")
        interface_class = "".join(x.capitalize() for x in interface_name.split("_"))

        if interface_name == self._interface_name:
            return ":class:`{}`".format(interface_class)

        if (
            self._interface_imports is not None
            and interface_name in self._interface_imports
        ):
            protocol_path = self._interface_imports[interface_name]
            return ":class:`~{base_path}.{iface}.{class_name}`".format(
                class_name=interface_class, base_path=BASE_PATH, iface=protocol_path,
            )

        return "`{}`".format(interface_class) 
Example #6
Source File: capitalization.py    From zulip with Apache License 2.0 6 votes vote down vote up
def replace_with_safe_phrase(matchobj: Match[str]) -> str:
    """
    The idea is to convert IGNORED_PHRASES into safe phrases, see
    `get_safe_phrase()` function. The only exception is when the
    IGNORED_PHRASE is at the start of the text or after a split
    boundary; in this case, we change the first letter of the phrase
    to upper case.
    """
    ignored_phrase = matchobj.group(0)
    safe_string = get_safe_phrase(ignored_phrase)

    start_index = matchobj.start()
    complete_string = matchobj.string

    is_string_start = start_index == 0
    # We expect that there will be one space between split boundary
    # and the next word.
    punctuation = complete_string[max(start_index - 2, 0)]
    is_after_split_boundary = punctuation in SPLIT_BOUNDARY
    if is_string_start or is_after_split_boundary:
        return safe_string.capitalize()

    return safe_string 
Example #7
Source File: BashFormatting.py    From ProjectAlice with GNU General Public License v3.0 6 votes vote down vote up
def colorFormat(m: Match) -> str:
		color = m.group(1).title()

		if color == 'red':
			code = BashStringFormatCode.RED.value
		elif color == 'green':
			code = BashStringFormatCode.GREEN.value
		elif color == 'yellow':
			code = BashStringFormatCode.YELLOW.value
		elif color == 'blue':
			code = BashStringFormatCode.BLUE.value
		elif color == 'grey':
			code = BashStringFormatCode.GREY.value
		else:
			code = BashStringFormatCode.DEFAULT.value

		return BashStringFormatCode.SEQUENCE.value.format(code, m.group(2), BashStringFormatCode.DEFAULT) 
Example #8
Source File: youtube.py    From CloudBot with GNU General Public License v3.0 6 votes vote down vote up
def ytplaylist_url(match: Match[str]) -> str:
    location = match.group(4).split("=")[-1]
    request = get_playlist(location, ["contentDetails", "snippet"])
    raise_api_errors(request)

    json = request.json()

    data = json["items"]
    if not data:
        raise NoResultsError()

    item = data[0]
    snippet = item["snippet"]
    content_details = item["contentDetails"]

    title = snippet["title"]
    author = snippet["channelTitle"]
    num_videos = int(content_details["itemCount"])
    count_videos = " - \x02{:,}\x02 video{}".format(num_videos, "s"[num_videos == 1 :])
    return "\x02{}\x02 {} - \x02{}\x02".format(title, count_videos, author) 
Example #9
Source File: instantiate.py    From nevergrad with MIT License 6 votes vote down vote up
def sub(cls, text: str, extension: str, replacers: Dict[str, Any]) -> str:
        found: Set[str] = set()
        kwargs = {x: _convert_to_string(y, extension) for x, y in replacers.items()}

        def _replacer(regex: Match[str]) -> str:
            name = regex.group("name")
            if name in found:
                raise RuntimeError(f'Trying to remplace a second time placeholder "{name}"')
            if name not in kwargs:
                raise KeyError(f'Could not find a value for placeholder "{name}"')
            found.add(name)
            return str(kwargs[name])

        text = re.sub(cls.pattern, _replacer, text)
        missing = set(kwargs) - found
        if missing:
            raise RuntimeError(f"All values have not been consumed: {missing}")
        return text 
Example #10
Source File: SettingDefinition.py    From Uranium with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _toFloatConversion(value: str) -> float:
    """Conversion of string to float."""

    value = value.replace(",", ".")
    """Ensure that all , are replaced with . (so they are seen as floats)"""

    def stripLeading0(matchobj: Match[str]) -> str:
        return matchobj.group(0).lstrip("0")

    regex_pattern = r"(?<!\.|\w|\d)0+(\d+)"
    """Literal eval does not like "02" as a value, but users see this as "2"."""
    """We therefore look numbers with leading "0", provided they are not used in variable names"""
    """example: "test02 * 20" should not be changed, but "test * 02 * 20" should be changed (into "test * 2 * 20")"""
    value = re.sub(regex_pattern, stripLeading0, value)

    try:
        return ast.literal_eval(value)
    except:
        return 0 
Example #11
Source File: scrape_bugblog.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 6 votes vote down vote up
def check_if_removed_from_bugblog(bbt: Match, b: Tag, issue: Issue) -> None:
    if bbt is not None:
        text = strings.remove_smartquotes(bbt.group(1).strip())
        for row in b.find_all('tr'):
            data = row.find_all('td')
            rowtext = strings.remove_smartquotes(data[1].text.strip())
            if rowtext == text:
                break
            if strip_squarebrackets(rowtext) == strip_squarebrackets(text):
                # Fix this
                print("Issue #{id}'s bug blog text has differing autocard notation.".format(id=issue.number))
                old_bbt = strings.get_body_field(issue.body, 'Bug Blog Text')
                body = re.sub(BBT_REGEX, 'Bug Blog Text: {0}'.format(rowtext), issue.body, flags=re.MULTILINE)
                new_bbt = strings.get_body_field(body, 'Bug Blog Text')
                issue.edit(body=body)
                print('Updated to `{0}`'.format(rowtext))
                issue.create_comment(f'Changed bug blog text from `{old_bbt}` to `{new_bbt}`')
                break
        else:
            print('{id} is fixed!'.format(id=issue.number))
            repo.create_comment(issue, 'This bug has been removed from the bug blog!')
            issue.edit(state='closed') 
Example #12
Source File: _data_types.py    From aws-data-wrangler with Apache License 2.0 6 votes vote down vote up
def process_not_inferred_dtype(ex: pa.ArrowInvalid) -> pa.DataType:
    """Infer data type from PyArrow inference exception."""
    ex_str = str(ex)
    _logger.debug("PyArrow was not able to infer data type:\n%s", ex_str)
    match: Optional[Match] = re.search(
        pattern="Could not convert (.*) with type (.*): did not recognize "
        "Python value type when inferring an Arrow data type",
        string=ex_str,
    )
    if match is None:
        raise ex  # pragma: no cover
    groups: Optional[Sequence[str]] = match.groups()
    if groups is None:
        raise ex  # pragma: no cover
    if len(groups) != 2:
        raise ex  # pragma: no cover
    _logger.debug("groups: %s", groups)
    type_str: str = groups[1]
    if type_str == "UUID":
        return pa.string()
    raise ex  # pragma: no cover 
Example #13
Source File: output_mask.py    From telepresence with Apache License 2.0 6 votes vote down vote up
def _replace_closure(replacement: str, m: Match[str]) -> str:
    def _replace_group(index: int) -> str:
        before = m.span(index)[0] - m.span()[0]
        after = m.span(index)[1] - m.span()[0]
        group = m.group()
        return group[:before] + replacement + group[after:]

    if m.group('in_double_quotes') is not None:
        return _replace_group(2)

    if m.group('in_single_quotes') is not None:
        return _replace_group(3)

    if m.group('plain_value') is not None:
        return _replace_group(4)

    assert False, m 
Example #14
Source File: client.py    From nats-python with MIT License 5 votes vote down vote up
def _recv(self, *commands: Pattern[bytes]) -> Tuple[Pattern[bytes], Match[bytes]]:
        line = self._readline()

        command = self._get_command(line)
        if command not in commands:
            raise NATSUnexpectedResponse(line)

        result = command.match(line)
        if result is None:
            raise NATSInvalidResponse(line)

        return command, result 
Example #15
Source File: HtmlFormatting.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
def colorFormat(m: Match) -> str:
		color = m.group(1).title()
		return HtmlFormatting.INLINE.value.format(f'log{color}', m.group(2)) 
Example #16
Source File: utils.py    From ipmininet with GNU General Public License v2.0 5 votes vote down vote up
def search_dns_reply(reply: str, regex: Pattern) \
        -> Tuple[bool, Optional[Match]]:

    got_answer = False
    for line in reply.split("\n"):
        if got_answer:
            if "SECTION" in line:
                break  # End of the answer section
            match = regex.match(line)
            if match is not None:
                return True, match  # Got the right answer
        elif ";; ANSWER SECTION:" in line:  # Beginning of the answer section
            got_answer = True
    return got_answer, None 
Example #17
Source File: operand.py    From VUT-FIT-IFJ-2017-toolkit with GNU General Public License v3.0 5 votes vote down vote up
def _resolve_constant(self, constant_match: Match[str]) -> None:
        type_, value = constant_match.groups()  # type: str, str
        type_ = type_.lower().strip()
        try:
            self.value = self.CONSTANT_MAPPING.get(type_)(value)
            if type_ == self.CONSTANT_MAPPING_REVERSE.get(bool):
                self.value = self.BOOL_LITERAL_MAPPING.get(value.lower())
            elif type_ == self.CONSTANT_MAPPING_REVERSE.get(str):
                self.value = unquote_escape_sequences(value=self.value)
        except ValueError:
            pass
        if self.value is None:
            raise InvalidCodeException(type_=InvalidCodeException.INVALID_OPERAND)
        self.type = TypeOperand.CONSTANT 
Example #18
Source File: operand.py    From VUT-FIT-IFJ-2017-toolkit with GNU General Public License v3.0 5 votes vote down vote up
def _resolve_variable(self, variable_match: Match[str]) -> None:
        # type: (Match) -> None
        frame, name = variable_match.groups()
        if not (frame and name):
            raise InvalidCodeException(type_=InvalidCodeException.INVALID_OPERAND)
        self.frame = frame
        self.name = name
        self.type = TypeOperand.VARIABLE 
Example #19
Source File: operand.py    From VUT-FIT-IFJ-2017-toolkit with GNU General Public License v3.0 5 votes vote down vote up
def _resolve_type(self, type_match: Match[str]) -> None:
        # type: (Match[str]) -> None
        self.data_type = type_match.group(1).lower()
        if self.data_type not in self.CONSTANT_MAPPING:
            raise InvalidCodeException(type_=InvalidCodeException.INVALID_OPERAND)
        self.type = TypeOperand.DATA_TYPE 
Example #20
Source File: pytype_test.py    From typeshed with Apache License 2.0 5 votes vote down vote up
def search(self, path: str) -> Optional[Match[str]]:
        if not self.matcher:
            return None
        return self.matcher.search(path) 
Example #21
Source File: Widget.py    From ProjectAlice with GNU General Public License v3.0 5 votes vote down vote up
def langReplace(self, match: Match):
		return self.getLanguageString(match.group(1)) 
Example #22
Source File: junitxml.py    From pytest with MIT License 5 votes vote down vote up
def bin_xml_escape(arg: str) -> py.xml.raw:
    def repl(matchobj: Match[str]) -> str:
        i = ord(matchobj.group())
        if i <= 0xFF:
            return "#x%02X" % i
        else:
            return "#x%04X" % i

    return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg))) 
Example #23
Source File: _fonem.py    From abydos with GNU General Public License v3.0 5 votes vote down vote up
def _get_parts(m: Match[str]) -> str:
    return (m.group(1) or '') + (m.group(2) or '') 
Example #24
Source File: _emoji_replace.py    From rich with MIT License 5 votes vote down vote up
def _emoji_replace(text: str, _emoji_sub=re.compile(r"(:(\S*?):)").sub) -> str:
    """Replace emoji code in text."""
    get_emoji = EMOJI.get

    def do_replace(match: Match[str]) -> str:
        """Called by re.sub to do the replacement."""
        emoji_code, emoji_name = match.groups()
        return get_emoji(emoji_name.lower(), emoji_code)

    return _emoji_sub(do_replace, text) 
Example #25
Source File: escape.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _convert_entity(m: typing.Match) -> str:
    if m.group(1) == "#":
        try:
            if m.group(2)[:1].lower() == "x":
                return chr(int(m.group(2)[1:], 16))
            else:
                return chr(int(m.group(2)))
        except ValueError:
            return "&#%s;" % m.group(2)
    try:
        return _HTML_UNICODE_MAP[m.group(2)]
    except KeyError:
        return "&%s;" % m.group(2) 
Example #26
Source File: escape.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _convert_entity(m: typing.Match) -> str:
    if m.group(1) == "#":
        try:
            if m.group(2)[:1].lower() == "x":
                return chr(int(m.group(2)[1:], 16))
            else:
                return chr(int(m.group(2)))
        except ValueError:
            return "&#%s;" % m.group(2)
    try:
        return _HTML_UNICODE_MAP[m.group(2)]
    except KeyError:
        return "&%s;" % m.group(2) 
Example #27
Source File: pyupgrade.py    From pyupgrade with MIT License 5 votes vote down vote up
def _must_match(regex: Pattern[str], string: str, pos: int) -> Match[str]:
    match = regex.match(string, pos)
    assert match is not None
    return match 
Example #28
Source File: pyupgrade.py    From pyupgrade with MIT License 5 votes vote down vote up
def _fix_ur_literals(token: Token) -> Token:
    prefix, rest = parse_string_literal(token.src)
    if prefix.lower() != 'ur':
        return token
    else:
        def cb(match: Match[str]) -> str:
            escape = match.group()
            if escape[1].lower() == 'u':
                return escape
            else:
                return '\\' + match.group()

        rest = ESCAPE_RE.sub(cb, rest)
        prefix = prefix.replace('r', '').replace('R', '')
        return token._replace(src=prefix + rest) 
Example #29
Source File: render_json.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def _encode_str(s: str) -> str:
    def replace(match: typing.Match[str]) -> str:
        return ESCAPE_DCT[match.group(0)]
    return '"' + ESCAPE.sub(replace, s) + '"' 
Example #30
Source File: block.py    From marko with MIT License 5 votes vote down vote up
def match(cls, source):  # type: (Source) -> Optional[Match]
        return source.expect_re(r" {,3}>")