potaahto

Conversions and redundancy for partisan naming choices
git clone git://git.defalsify.org/python-potaahto.git
Info | Log | Files | Refs | LICENSE

symbols.py (1737B)


      1 # standard imports
      2 import re
      3 
      4 re_camel = re.compile(r'([a-z0-9]+)([A-Z])')
      5 re_snake = re.compile(r'([a-z0-9]+)_([A-Za-z])')
      6 
      7 
      8 def camel_to_snake(k):
      9     s_snake = ''
     10     right_pos = 0
     11     for m in re_camel.finditer(k):
     12         g = m.group(0)
     13         s_snake += g[:len(g)-1]
     14         s_snake += '_' + g[len(g)-1].lower()
     15         right_pos = m.span()[1]
     16     s_snake += k[right_pos:]
     17     return s_snake
     18 
     19 
     20 def snake_to_camel(k):
     21     s_camel = ''
     22     right_pos = 0
     23     for m in re_snake.finditer(k):
     24         g = m.group(0)
     25         s_camel += g[:len(g)-2]
     26         s_camel += g[len(g)-1].upper()
     27         right_pos = m.span()[1]
     28     s_camel += k[right_pos:]
     29     return s_camel
     30 
     31 
     32 def snake_and_camel_s(k):
     33     s_camel = camel_to_snake(k)
     34     s_snake = snake_to_camel(k)
     35     return (s_snake, s_camel)
     36 
     37 
     38 def snake_and_camel(src):
     39     src_normal = {}
     40     for k in src.keys():
     41         (s_snake, s_camel) = snake_and_camel_s(k) 
     42         src_normal[k] = src[k]
     43         #if s != k:
     44         if k != s_snake:
     45             src_normal[s_snake] = src[k]
     46 
     47         if k != s_camel:
     48             src_normal[s_camel] = src[k]
     49 
     50     return src_normal
     51 
     52 
     53 def ensure_key(src, key, default_value):
     54     (s_snake, s_camel) = snake_and_camel_s(key)
     55     try:
     56         v = src[s_snake]
     57     except KeyError:
     58         try:
     59             v = src[s_camel]
     60         except KeyError:
     61             src[key] = default_value
     62     return src
     63 
     64 
     65 def mimic_key(src, key_one, key_two, default_value=None):
     66     v = None
     67     try:
     68         v = src[key_one]
     69     except KeyError:
     70         try:
     71             v = src[key_two]
     72         except KeyError:
     73             if default_value != None:
     74                 v = default_value
     75 
     76     if v != None:
     77         src[key_one] = v
     78         src[key_two] = v
     79     return src