Login

Replacing pattern groups by values

Author:
marinho
Posted:
August 17, 2011
Language:
Python
Version:
1.3
Score:
-1 (after 1 ratings)

This function takes a pattern with groups and replaces 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.

When both args and kwargs are given, raises a ValueError.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months 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 :)

#

mariorojas (on April 9, 2023):

hey

#

Please login first before commenting.