Replacing pattern groups by values

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import re

def replace_groups(pattern, args=None, kwargs=None):
    """
    This function takes a pattern with groups and replace them with the given args and/or
    kwargs. Example:

    IMPORTANT: this code is NOT to use replacing Django's reverse function. The
    example below is just to illustrate how it works.

    For a given pattern '/docs/(\d+)/rev/(\w+)/', args=(123,'abc') and kwargs={},
    returns '/docs/123/rev/abc/'.

    For '/docs/(?P<id>\d+)/rev/(?P<rev>\w+)/', args=() and kwargs={'rev':'abc', 'id':123}
    returns '/docs/123/rev/abc/' as well.

    For now, when both args and kwargs are given, raises a ValueError.
    """
    if args and kwargs:
        raise ValueError("Informed both *args and **kwargs it's not supported.")
    
    exp_kwarg = re.compile('^\(\?P<(\w+)>(.+)\)$') # Used to check named arguments

    new = ''
    cur_group = ''
    group_count = 0

    for ch in pattern:
        if ch == '(':
            group_count += 1
            cur_group += ch
        elif ch == ')':
            group_count -= 1
            cur_group += ch

            if not group_count:
                m_kwarg = exp_kwarg.match(cur_group)

                if m_kwarg:
                    value = str(kwargs.pop(m_kwarg.group(1)))
                else:
                    value = str(args[0])
                    args = args[1:]

                if re.match('^%s$'%cur_group, value):
                    new += value
                    cur_group = ''
        elif group_count:
            cur_group += ch
        else:
            new += ch

    return new

More like this

  1. Resolve URLs to view name and args/kwargs by fahhem 3 years, 5 months ago
  2. Parse custom template tag's args or kwargs by t_rybik 3 years, 7 months ago
  3. packjs templatetag by kyprizel 6 years, 3 months ago
  4. CallTag - Just like include, but can pass parameters to it by limodou 7 years, 1 month ago
  5. Wrapper-function Pattern by Archatas 4 years ago

Comments

adamlofts (on August 17, 2011):

I guess you've looked at django.core.urlresolvers.reverse?

#

marinho (on August 22, 2011):

Adam, yes, I know it, but it's totally another approach for this, and actually, I disagree the way it does and I see it as a really ugly code (one of the ugliest in Django code).

#

marinho (on August 22, 2011):

But, BTW, this is not being used as a replacement for reverse. I used the URL example just to make it easier to understand for who is reading :)

#

(Forgotten your password?)