regular expression that we are creating. line 11 : This contains the position of the end of the last match. line 12 : The finditer method yields all the matches. line 13 : We're getting all the non- {} text from after the last match, up to the beginning of this match. We call re.escape on that text, which escapes any characters that have special meaning. So .html will be escaped as \.html . line 14 : The first match is the variable name. line 15 : expr is the regular expression we'll match against, the optional second match. The default is [^/]+ , which matches any non-empty, non-/ string. Which seems like a reasonable default to me. line 16 : Here we create the actual regular expression. (?P&lt;name&gt;...) is a grouped expression that is named. When you get a match, you can look at match.groupdict() and get the names and values. line 17, 18 : We add the expression on to the complete regular expression and save the last position. line 20 : And then we make the regular expression match the complete string ( ^ to force it to match from the start, $ to make sure it matches up to the end). To test it we can try some translations. You could put these directly in the docstring of the template_to_regex function and use doctest to test that. But I'm using doctest to test this document, so I can't put a docstring doctest inside the doctest itself.