ATLAS Offline Software
split_list.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
2 
3 def split_list1 (l, delim):
4  """Split the string L at the character DELIM.
5 But don't split within groups nested in ([{}]) or in strings.
6 
7 >>> split_list1 ('12345', ',')
8 ['12345']
9 >>> split_list1 ('123, [45, 67], (89,[10,11],12), 13', ',')
10 ['123', '[45, 67]', '(89,[10,11],12)', '13']
11 >>> split_list1 ('12, "34,56", 78', ',')
12 ['12', '"34,56"', '78']
13 >>> dq='"'
14 >>> sq="'"
15 >>> bs='\\\\'
16 >>> len(bs)
17 1
18 >>> split_list1 ('12, "34,56", '+sq+'11,12'+sq+', 78', ',')
19 ['12', '"34,56"', "'11,12'", '78']
20 >>> split_list1 ('12, "34,56'+bs+dq+',99", '+sq+'11,12'+sq+', 78', ',')
21 ['12', '"34,56\\\\",99"', "'11,12'", '78']
22 >>> split_list1 ('12, "34,56'+bs+bs+dq+',99, '+sq+'11,12'+sq+', 78', ',')
23 ['12', '"34,56\\\\\\\\"', '99', "'11,12'", '78']
24 """
25  i = 0
26  out = []
27  sz = len(l)
28  while i < sz:
29  nest = 0
30  j = i
31  while j < sz:
32  c = l[j]
33  if c == delim and nest == 0:
34  break
35  elif c in '[{(':
36  nest += 1
37  elif c in '])}':
38  if nest == 0: break
39  nest -= 1
40  elif c in '\'"':
41  j += 1
42  esc = False
43  while j < sz and not (l[j] == c and not esc):
44  if esc:
45  esc = False
46  elif l[j] == '\\':
47  esc = True
48  j += 1
49  j += 1
50  out.append (l[i:j])
51  i = j+1
52  while i < sz and l[i] == ' ':
53  i += 1
54  return out
55 
56 
57 def split_list (l):
58  """L is a string representation of a list. Split it at commas.
59 But don't split within groups nested in ([{}]) or in strings.
60 
61 >>> split_list ('[12345]')
62 ['12345']
63 >>> split_list ('[123,[45,67],(89,[10,11],12),13]')
64 ['123', '[45,67]', '(89,[10,11],12)', '13']
65 """
66  return split_list1 (l[1:-1], ',')
67 
68 
69 if __name__ == '__main__':
70  from PyUtils import coverage #pragma: NO COVER
71  c = coverage.Coverage ('D3PDMakerTest.split_list') #pragma: NO COVER
72  c.doctest_cover () #pragma: NO COVER
python.coverage.Coverage
Definition: coverage.py:149
python.split_list.split_list
def split_list(l)
Definition: split_list.py:57
python.split_list.split_list1
def split_list1(l, delim)
Definition: split_list.py:3