Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2015
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. def removeTemplateArguments(str, depthToRemove):
  2. """ Remove template arguments deeper than depthToRemove
  3. so removeTemplateArguments("foo<int>()", 1) gives foo<>()
  4. removeTemplateArguments("foo< bar<int> >()", 1) gives foo< >()
  5. removeTemplateArguments("foo< bar<int> >()", 2) gives foo< bar<> >()"""
  6. if depthToRemove <= 0:
  7. return str
  8. currDepth = 0
  9. res = ""
  10. for c in str:
  11. if currDepth < depthToRemove:
  12. res += c
  13. if c == "<":
  14. currDepth += 1
  15. elif c == ">":
  16. currDepth -= 1
  17. if currDepth < depthToRemove:
  18. res += ">"
  19. return res
  20.  
  21. from itertools import groupby
  22.  
  23. def remove_arguments(template, depth):
  24. res = []
  25. curr_depth = 0
  26. for k,g in groupby(template, lambda x: x in ['<', '>']):
  27. text = ''.join(g) # rebuild the group as a string
  28. if text == '<':
  29. curr_depth += 1
  30.  
  31. # it's important to put this part in the middle
  32. if curr_depth < depth:
  33. res.append(text)
  34. elif k and curr_depth == depth: # add the inner <>
  35. res.append(text)
  36.  
  37. if text == '>':
  38. curr_depth -= 1
  39.  
  40. return ''.join(res) # rebuild the complete string
  41.  
  42. >>> remove_arguments('foo<int>()', 1)
  43. foo<>()
  44. >>> remove_arguments('foo< bar<int> >()', 1)
  45. foo<>()
  46. >>> remove_arguments('foo< bar<int> >()', 2)
  47. foo< bar<> >()
  48. >>> remove_arguments('foo< bar >()', 2)
  49. foo< bar >()
  50.  
  51. groupby(template, lambda x: x in ['<', '>']) # most obvious one
  52. groupby(template, lambda x: x in '<>') # equivalent to the one above
  53. groupby(template, '<>'.__contains__) # this is ugly ugly
  54. groupby(template, '<>'.count) # not obvious, but looks sweet
  55.  
  56. def get_level(ch, level=[0]):
  57. current = level[0]
  58. if ch == '<':
  59. level[0] += 1
  60. if ch == '>':
  61. level[0] -= 1
  62. current = level[0]
  63.  
  64. return current
  65.  
  66. def remove_arguments(template, depth):
  67. res = []
  68. for k,g in groupby(template, get_level):
  69. if k < depth:
  70. res.append(''.join(g))
  71. return ''.join(res)
  72.  
  73. import re
  74.  
  75. def removeTemplateArguments(function_name, depth):
  76. to_match = "(?P<class>w+)<s*(?P<nested>.*)s*>(?P<paren>(?)?)"
  77. parts = re.match(to_match, function_name).groupdict()
  78. nested = '' if depthToRemove == 1
  79. else removeTemplateArguments(parts['nested'], depth-1)
  80.  
  81. return "%s<%s>%s" % (parts['class'], nested, parts['paren'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement