77
88import re
99
10+ verbose = False
11+
12+ _nameRE = re .compile (r'\w+' )
13+ _equalsRE = re .compile (r'\=' )
14+ _stringRE = re .compile (r'''"[^"]+"|'[^']+'|\S+''' )
15+ _whiteRE = re .compile (r'\s+' )
16+
17+ _REs = {_nameRE : 'name' , _equalsRE : 'equals' ,
18+ _stringRE : 'string' , _whiteRE : 'white' }
19+
1020
1121class DictForArgsError (Exception ):
1222 """Error when building dictionary from arguments."""
@@ -16,14 +26,6 @@ def _SyntaxError(s):
1626 raise DictForArgsError (f'Syntax error: { s !r} ' )
1727
1828
19- _nameRE = re .compile (r'\w+' )
20- _equalsRE = re .compile (r'\=' )
21- _stringRE = re .compile (r'''"[^"]+"|'[^']+'|\S+''' )
22- _whiteRE = re .compile (r'\s+' )
23-
24- _REs = [_nameRE , _equalsRE , _stringRE , _whiteRE ]
25-
26-
2729def dictForArgs (s ):
2830 """Build dictionary from arguments.
2931
@@ -58,7 +60,6 @@ def dictForArgs(s):
5860
5961 # Tokenize
6062
61- verbose = False
6263 matches = []
6364 start = 0
6465 sLen = len (s )
@@ -84,17 +85,7 @@ def dictForArgs(s):
8485 _SyntaxError (s )
8586
8687 if verbose :
87- names = []
88- for match in matches :
89- if match .re is _nameRE :
90- name = 'name'
91- elif match .re is _equalsRE :
92- name = 'equals'
93- elif match .re is _stringRE :
94- name = 'string'
95- elif match .re is _whiteRE :
96- name = 'white'
97- names .append (name )
88+ names = ', ' .join (_REs [match .re ] for match in matches )
9889 print ('>> names =' , names )
9990
10091 # Process tokens
@@ -107,10 +98,7 @@ def dictForArgs(s):
10798 i = 0
10899 while i < matchesLen :
109100 match = matches [i ]
110- if i + 1 < matchesLen :
111- peekMatch = matches [i + 1 ]
112- else :
113- peekMatch = None
101+ peekMatch = matches [i + 1 ] if i + 1 < matchesLen else None
114102 if match .re is _nameRE :
115103 if peekMatch is not None :
116104 if peekMatch .re is _nameRE :
@@ -121,9 +109,9 @@ def dictForArgs(s):
121109 if peekMatch .re is _equalsRE :
122110 if i + 2 < matchesLen :
123111 target = matches [i + 2 ]
124- if target .re is _nameRE or target . re is _stringRE :
112+ if target .re in ( _nameRE , _stringRE ) :
125113 value = target .group ()
126- if value [0 ] == "'" or value [ 0 ] == '"' :
114+ if value [0 ] in ( "'" , '"' ) :
127115 value = value [1 :- 1 ]
128116 d [match .group ()] = value
129117 i += 3
0 commit comments