Skip to content

Commit

Permalink
Use typing.Self where applicable
Browse files Browse the repository at this point in the history
  • Loading branch information
InSyncWithFoo committed Jan 12, 2024
1 parent 2a1a8e8 commit d2506b5
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 35 deletions.
74 changes: 39 additions & 35 deletions pyparsing/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
Tuple,
Union,
cast,
TYPE_CHECKING
)
from abc import ABC, abstractmethod
from enum import Enum
Expand Down Expand Up @@ -50,6 +51,9 @@
from .results import ParseResults, _ParseResultsWithOffset
from .unicode import pyparsing_unicode

if TYPE_CHECKING:
from typing_extensions import Self

_MAX_INT = sys.maxsize
str_type: Tuple[type, ...] = (str, bytes)

Expand Down Expand Up @@ -486,7 +490,7 @@ def __init__(self, savelist: bool = False):
self.callDuringTry = False
self.suppress_warnings_: List[Diagnostics] = []

def suppress_warning(self, warning_type: Diagnostics) -> "ParserElement":
def suppress_warning(self, warning_type: Diagnostics) -> "Self":
"""
Suppress warnings emitted for a particular diagnostic on this expression.
Expand Down Expand Up @@ -592,7 +596,7 @@ def _setResultsName(self, name, listAllMatches=False):
newself.modalResults = not listAllMatches
return newself

def set_break(self, break_flag: bool = True) -> "ParserElement":
def set_break(self, break_flag: bool = True) -> "Self":
"""
Method to invoke the Python pdb debugger when this element is
about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to
Expand All @@ -614,7 +618,7 @@ def breaker(instring, loc, doActions=True, callPreParse=True):
self._parse = self._parse._originalParseMethod # type: ignore [attr-defined, assignment]
return self

def set_parse_action(self, *fns: ParseAction, **kwargs) -> "ParserElement":
def set_parse_action(self, *fns: ParseAction, **kwargs) -> "Self":
"""
Define one or more actions to perform when successfully matching parse element definition.
Expand Down Expand Up @@ -702,7 +706,7 @@ def is_valid_date(instring, loc, toks):

return self

def add_parse_action(self, *fns: ParseAction, **kwargs) -> "ParserElement":
def add_parse_action(self, *fns: ParseAction, **kwargs) -> "Self":
"""
Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`.
Expand All @@ -714,7 +718,7 @@ def add_parse_action(self, *fns: ParseAction, **kwargs) -> "ParserElement":
)
return self

def add_condition(self, *fns: ParseCondition, **kwargs) -> "ParserElement":
def add_condition(self, *fns: ParseCondition, **kwargs) -> "Self":
"""Add a boolean predicate function to expression's list of parse actions. See
:class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``,
functions passed to ``add_condition`` need to return boolean success/fail of the condition.
Expand Down Expand Up @@ -751,7 +755,7 @@ def add_condition(self, *fns: ParseCondition, **kwargs) -> "ParserElement":
)
return self

def set_fail_action(self, fn: ParseFailAction) -> "ParserElement":
def set_fail_action(self, fn: ParseFailAction) -> "Self":
"""
Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
Expand Down Expand Up @@ -1730,7 +1734,7 @@ def suppress(self) -> "ParserElement":
"""
return Suppress(self)

def ignore_whitespace(self, recursive: bool = True) -> "ParserElement":
def ignore_whitespace(self, recursive: bool = True) -> "Self":
"""
Enables the skipping of whitespace before matching the characters in the
:class:`ParserElement`'s defined pattern.
Expand All @@ -1740,7 +1744,7 @@ def ignore_whitespace(self, recursive: bool = True) -> "ParserElement":
self.skipWhitespace = True
return self

def leave_whitespace(self, recursive: bool = True) -> "ParserElement":
def leave_whitespace(self, recursive: bool = True) -> "Self":
"""
Disables the skipping of whitespace before matching the characters in the
:class:`ParserElement`'s defined pattern. This is normally only used internally by
Expand All @@ -1753,7 +1757,7 @@ def leave_whitespace(self, recursive: bool = True) -> "ParserElement":

def set_whitespace_chars(
self, chars: Union[Set[str], str], copy_defaults: bool = False
) -> "ParserElement":
) -> "Self":
"""
Overrides the default whitespace chars
"""
Expand All @@ -1762,7 +1766,7 @@ def set_whitespace_chars(
self.copyDefaultWhiteChars = copy_defaults
return self

def parse_with_tabs(self) -> "ParserElement":
def parse_with_tabs(self) -> "Self":
"""
Overrides default behavior to expand ``<TAB>`` s to spaces before parsing the input string.
Must be called before ``parse_string`` when the input grammar contains elements that
Expand All @@ -1771,7 +1775,7 @@ def parse_with_tabs(self) -> "ParserElement":
self.keepTabs = True
return self

def ignore(self, other: "ParserElement") -> "ParserElement":
def ignore(self, other: "ParserElement") -> "Self":
"""
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
Expand Down Expand Up @@ -1802,7 +1806,7 @@ def set_debug_actions(
start_action: DebugStartAction,
success_action: DebugSuccessAction,
exception_action: DebugExceptionAction,
) -> "ParserElement":
) -> "Self":
"""
Customize display of debugging messages while doing pattern matching:
Expand All @@ -1823,7 +1827,7 @@ def set_debug_actions(
self.debug = True
return self

def set_debug(self, flag: bool = True, recurse: bool = False) -> "ParserElement":
def set_debug(self, flag: bool = True, recurse: bool = False) -> "Self":
"""
Enable display of debugging messages while doing pattern matching.
Set ``flag`` to ``True`` to enable, ``False`` to disable.
Expand Down Expand Up @@ -1888,7 +1892,7 @@ def _generateDefaultName(self) -> str:
Child classes must define this method, which defines how the ``default_name`` is set.
"""

def set_name(self, name: str) -> "ParserElement":
def set_name(self, name: str) -> "Self":
"""
Define name for this expression, makes debugging and exception messages clearer.
Expand All @@ -1914,7 +1918,7 @@ def __str__(self) -> str:
def __repr__(self) -> str:
return str(self)

def streamline(self) -> "ParserElement":
def streamline(self) -> "Self":
self.streamlined = True
self._defaultName = None
return self
Expand Down Expand Up @@ -3739,12 +3743,12 @@ def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False
def recurse(self) -> List[ParserElement]:
return self.exprs[:]

def append(self, other) -> ParserElement:
def append(self, other) -> "Self":
self.exprs.append(other)
self._defaultName = None
return self

def leave_whitespace(self, recursive: bool = True) -> ParserElement:
def leave_whitespace(self, recursive: bool = True) -> "Self":
"""
Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on
all contained expressions.
Expand All @@ -3757,7 +3761,7 @@ def leave_whitespace(self, recursive: bool = True) -> ParserElement:
e.leave_whitespace(recursive)
return self

def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
def ignore_whitespace(self, recursive: bool = True) -> "Self":
"""
Extends ``ignore_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on
all contained expressions.
Expand All @@ -3769,7 +3773,7 @@ def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
e.ignore_whitespace(recursive)
return self

def ignore(self, other) -> ParserElement:
def ignore(self, other) -> "Self":
if isinstance(other, Suppress):
if other not in self.ignoreExprs:
super().ignore(other)
Expand All @@ -3784,7 +3788,7 @@ def ignore(self, other) -> ParserElement:
def _generateDefaultName(self) -> str:
return f"{self.__class__.__name__}:({self.exprs})"

def streamline(self) -> ParserElement:
def streamline(self) -> "Self":
if self.streamlined:
return self

Expand Down Expand Up @@ -3934,7 +3938,7 @@ def __init__(
self.mayReturnEmpty = True
self.callPreparse = True

def streamline(self) -> ParserElement:
def streamline(self) -> "Self":
# collapse any _PendingSkip's
if self.exprs and any(
isinstance(e, ParseExpression)
Expand Down Expand Up @@ -4061,7 +4065,7 @@ def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False
else:
self.mayReturnEmpty = True

def streamline(self) -> ParserElement:
def streamline(self) -> "Self":
super().streamline()
if self.exprs:
self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
Expand Down Expand Up @@ -4216,7 +4220,7 @@ def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False
else:
self.mayReturnEmpty = True

def streamline(self) -> ParserElement:
def streamline(self) -> "Self":
if self.streamlined:
return self

Expand Down Expand Up @@ -4372,7 +4376,7 @@ def __iand__(self, other):
return NotImplemented
return self.append(other) # Each([self, other])

def streamline(self) -> ParserElement:
def streamline(self) -> "Self":
super().streamline()
if self.exprs:
self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
Expand Down Expand Up @@ -4513,7 +4517,7 @@ def parseImpl(self, instring, loc, doActions=True):
pbe.msg = self.errmsg
raise

def leave_whitespace(self, recursive: bool = True) -> ParserElement:
def leave_whitespace(self, recursive: bool = True) -> "Self":
super().leave_whitespace(recursive)

if recursive:
Expand All @@ -4522,7 +4526,7 @@ def leave_whitespace(self, recursive: bool = True) -> ParserElement:
self.expr.leave_whitespace(recursive)
return self

def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
def ignore_whitespace(self, recursive: bool = True) -> "Self":
super().ignore_whitespace(recursive)

if recursive:
Expand All @@ -4531,15 +4535,15 @@ def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
self.expr.ignore_whitespace(recursive)
return self

def ignore(self, other) -> ParserElement:
def ignore(self, other) -> "Self":
if not isinstance(other, Suppress) or other not in self.ignoreExprs:
super().ignore(other)
if self.expr is not None:
self.expr.ignore(self.ignoreExprs[-1])

return self

def streamline(self) -> ParserElement:
def streamline(self) -> "Self":
super().streamline()
if self.expr is not None:
self.expr.streamline()
Expand Down Expand Up @@ -4913,7 +4917,7 @@ def __init__(
ender = self._literalStringClass(ender)
self.stopOn(ender)

def stopOn(self, ender) -> ParserElement:
def stopOn(self, ender) -> "Self":
if isinstance(ender, str_type):
ender = self._literalStringClass(ender)
self.not_ender = ~ender if ender is not None else None
Expand Down Expand Up @@ -5372,7 +5376,7 @@ def __init__(self, other: typing.Optional[Union[ParserElement, str]] = None):
super().__init__(other, savelist=False) # type: ignore[arg-type]
self.lshift_line = None

def __lshift__(self, other) -> "Forward":
def __lshift__(self, other) -> "Self":
if hasattr(self, "caller_frame"):
del self.caller_frame
if isinstance(other, str_type):
Expand Down Expand Up @@ -5523,15 +5527,15 @@ def parseImpl(self, instring, loc, doActions=True):
raise
prev_loc, prev_peek = memo[peek_key] = new_loc, new_peek

def leave_whitespace(self, recursive: bool = True) -> ParserElement:
def leave_whitespace(self, recursive: bool = True) -> "Self":
self.skipWhitespace = False
return self

def ignore_whitespace(self, recursive: bool = True) -> ParserElement:
def ignore_whitespace(self, recursive: bool = True) -> "Self":
self.skipWhitespace = True
return self

def streamline(self) -> ParserElement:
def streamline(self) -> "Self":
if not self.streamlined:
self.streamlined = True
if self.expr is not None:
Expand Down Expand Up @@ -5646,7 +5650,7 @@ def __init__(
self.joinString = joinString
self.callPreparse = True

def ignore(self, other) -> ParserElement:
def ignore(self, other) -> "Self":
if self.adjacent:
ParserElement.ignore(self, other)
else:
Expand Down Expand Up @@ -5841,7 +5845,7 @@ def __sub__(self, other) -> "ParserElement":
def postParse(self, instring, loc, tokenlist):
return []

def suppress(self) -> ParserElement:
def suppress(self) -> "Self":
return self


Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ diagrams = [
"railroad-diagrams",
"jinja2",
]
types = [
"typing_extensions"
]

[project.urls]
Homepage = "https://github.com/pyparsing/pyparsing/"
Expand Down

0 comments on commit d2506b5

Please sign in to comment.