MCPcopy Create free account
hub / github.com/numpy/numpy / lex

Function lex

tools/npy_tempita/__init__.py:638–698  ·  view source on GitHub ↗

Lex a string into chunks: >>> lex('hey') ['hey'] >>> lex('hey {{you}}') ['hey ', ('you', (1, 7))] >>> lex('hey {{') Traceback (most recent call last): ... tempita.TemplateError: No }} to finish last expression at line 1 column

(s, name=None, trim_whitespace=True, line_offset=0, delimiters=None)

Source from the content-addressed store, hash-verified

636
637
638def lex(s, name=None, trim_whitespace=True, line_offset=0, delimiters=None):
639 """
640 Lex a string into chunks:
641
642 >>> lex('hey')
643 ['hey']
644 >>> lex('hey {{you}}')
645 ['hey ', ('you', (1, 7))]
646 >>> lex('hey {{')
647 Traceback (most recent call last):
648 ...
649 tempita.TemplateError: No }} to finish last expression at line 1 column 7
650 >>> lex('hey }}')
651 Traceback (most recent call last):
652 ...
653 tempita.TemplateError: }} outside expression at line 1 column 7
654 >>> lex('hey {{ {{')
655 Traceback (most recent call last):
656 ...
657 tempita.TemplateError: {{ inside expression at line 1 column 10
658 """
659
660 if delimiters is None:
661 delimiters = (Template.default_namespace['start_braces'],
662 Template.default_namespace['end_braces'])
663 in_expr = False
664 chunks = []
665 last = 0
666 last_pos = (line_offset + 1, 1)
667 token_re = re.compile(r'%s|%s' % (re.escape(delimiters[0]),
668 re.escape(delimiters[1])))
669 for match in token_re.finditer(s):
670 expr = match.group(0)
671 pos = find_position(s, match.end(), last, last_pos)
672 if expr == delimiters[0] and in_expr:
673 raise TemplateError('%s inside expression' % delimiters[0],
674 position=pos,
675 name=name)
676 elif expr == delimiters[1] and not in_expr:
677 raise TemplateError('%s outside expression' % delimiters[1],
678 position=pos,
679 name=name)
680 if expr == delimiters[0]:
681 part = s[last:match.start()]
682 if part:
683 chunks.append(part)
684 in_expr = True
685 else:
686 chunks.append((s[last:match.start()], last_pos))
687 in_expr = False
688 last = match.end()
689 last_pos = pos
690 if in_expr:
691 raise TemplateError('No %s to finish last expression' % delimiters[1],
692 name=name, position=last_pos)
693 part = s[last:]
694 if part:
695 chunks.append(part)

Callers 1

parseFunction · 0.85

Calls 4

find_positionFunction · 0.85
TemplateErrorClass · 0.85
trim_lexFunction · 0.85
compileMethod · 0.45

Tested by

no test coverage detected