|
24 | 24 | 'Skip Montanaro, Raymond Hettinger, Trent Nelson, ' |
25 | 25 | 'Michael Foord') |
26 | 26 |
|
27 | | -import collections |
28 | 27 | import re, string, sys |
29 | 28 | from token import * |
30 | 29 | from codecs import lookup, BOM_UTF8 |
31 | 30 | cookie_re = re.compile("coding[:=]\s*([-\w.]+)") |
32 | 31 |
|
33 | 32 | import token |
34 | 33 | __all__ = [x for x in dir(token) if x[0] != '_'] + ["COMMENT", "tokenize", |
35 | | - "detect_encoding", "NL", "untokenize", "ENCODING", "Tokenize"] |
| 34 | + "detect_encoding", "NL", "untokenize", "ENCODING", "TokenInfo"] |
36 | 35 | del token |
37 | 36 |
|
38 | 37 | COMMENT = N_TOKENS |
|
43 | 42 | tok_name[ENCODING] = 'ENCODING' |
44 | 43 | N_TOKENS += 3 |
45 | 44 |
|
46 | | -TokenInfo = collections.namedtuple('TokenInfo', 'type string start end line') |
| 45 | +class TokenInfo(tuple): |
| 46 | + 'TokenInfo(type, string, start, end, line)' |
| 47 | + |
| 48 | + __slots__ = () |
| 49 | + |
| 50 | + _fields = ('type', 'string', 'start', 'end', 'line') |
| 51 | + |
| 52 | + def __new__(cls, type, string, start, end, line): |
| 53 | + return tuple.__new__(cls, (type, string, start, end, line)) |
| 54 | + |
| 55 | + @classmethod |
| 56 | + def _make(cls, iterable, new=tuple.__new__, len=len): |
| 57 | + 'Make a new TokenInfo object from a sequence or iterable' |
| 58 | + result = new(cls, iterable) |
| 59 | + if len(result) != 5: |
| 60 | + raise TypeError('Expected 5 arguments, got %d' % len(result)) |
| 61 | + return result |
| 62 | + |
| 63 | + def __repr__(self): |
| 64 | + return 'TokenInfo(type=%r, string=%r, start=%r, end=%r, line=%r)' % self |
| 65 | + |
| 66 | + def _asdict(self): |
| 67 | + 'Return a new dict which maps field names to their values' |
| 68 | + return dict(zip(self._fields, self)) |
| 69 | + |
| 70 | + def _replace(self, **kwds): |
| 71 | + 'Return a new TokenInfo object replacing specified fields with new values' |
| 72 | + result = self._make(map(kwds.pop, ('type', 'string', 'start', 'end', 'line'), self)) |
| 73 | + if kwds: |
| 74 | + raise ValueError('Got unexpected field names: %r' % kwds.keys()) |
| 75 | + return result |
| 76 | + |
| 77 | + def __getnewargs__(self): |
| 78 | + return tuple(self) |
| 79 | + |
| 80 | + type = property(lambda t: t[0]) |
| 81 | + string = property(lambda t: t[1]) |
| 82 | + start = property(lambda t: t[2]) |
| 83 | + end = property(lambda t: t[3]) |
| 84 | + line = property(lambda t: t[4]) |
47 | 85 |
|
48 | 86 | def group(*choices): return '(' + '|'.join(choices) + ')' |
49 | 87 | def any(*choices): return group(*choices) + '*' |
|
0 commit comments