Skip to content

Commit d82ae82

Browse files
committed
refactor: replace namedtuple with slotted class
for optimizing
1 parent 67af4ee commit d82ae82

File tree

3 files changed

+26
-18
lines changed

3 files changed

+26
-18
lines changed

peg_parser/subheader.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -604,7 +604,8 @@ def _strip_path_prefix(token: TokenInfo | Node) -> TokenInfo | None:
604604
prefix, text = text[:idx].lower(), text[idx:]
605605
if "p" in prefix:
606606
prefix = prefix.replace("p", "", 1)
607-
return token._replace(string=prefix + text)
607+
token.string = prefix + text
608+
return token
608609
return None
609610

610611
def extract_import_level(self, tokens: list[TokenInfo]) -> int:

peg_parser/tokenize.py

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
import itertools as _itertools
3636
import re
3737
from enum import Enum, auto
38-
from typing import TYPE_CHECKING, Any, Final, NamedTuple
38+
from typing import TYPE_CHECKING, Any, Final
3939

4040
if TYPE_CHECKING:
4141
from collections.abc import Callable, Generator, Iterator
@@ -135,11 +135,14 @@ class Token(Enum):
135135
WS = auto()
136136

137137

138-
class TokenInfo(NamedTuple):
139-
type: Token
140-
string: str
141-
start: tuple[int, int]
142-
end: tuple[int, int]
138+
class TokenInfo:
139+
__slots__ = ("end", "start", "string", "type")
140+
141+
def __init__(self, type: Token, string: str, start: tuple[int, int], end: tuple[int, int]):
142+
self.type = type
143+
self.string = string
144+
self.start = start
145+
self.end = end
143146

144147
def __repr__(self) -> str:
145148
return f"<{self.type.name}>({self.string!r}) at {self.start[0]}"
@@ -281,19 +284,25 @@ class TokenError(Exception):
281284
pass
282285

283286

284-
class ModeMiddle(NamedTuple):
285-
# in the string portion of an f-string (outside braces)
286-
parenlevel: int
287+
class ModeMiddle:
288+
__slots__ = ("parenlevel",)
289+
290+
def __init__(self, parenlevel: int):
291+
self.parenlevel = parenlevel
292+
287293

294+
class ModeInBraces:
295+
__slots__ = ("parenlevel",)
288296

289-
class ModeInBraces(NamedTuple):
290-
parenlevel: int
297+
def __init__(self, parenlevel: int):
298+
self.parenlevel = parenlevel
291299

292300

293-
class ModeInColon(NamedTuple):
294-
"""in the format specifier ({:*})"""
301+
class ModeInColon:
302+
__slots__ = ("parenlevel",)
295303

296-
parenlevel: int
304+
def __init__(self, parenlevel: int):
305+
self.parenlevel = parenlevel
297306

298307

299308
Mode = ModeMiddle | ModeInBraces | ModeInColon

xonsh_tokenizer/xonsh_tokenizer.pyi

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
from typing import NamedTuple
2-
3-
class TokenInfo(NamedTuple):
1+
class TokenInfo:
42
type: str
53
string: str
64
start: tuple[int, int]

0 commit comments

Comments
 (0)