Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes | Private Member Functions
MoinMoin.script.migration.wikiutil160a.ParameterParser Class Reference

List of all members.

Public Member Functions

def __init__
def __str__
def parse_parameters

Public Attributes

 param_re
 optional
 param_list
 param_dict

Private Member Functions

def _parse_pattern

Detailed Description

MoinMoin macro parameter parser

    Parses a given parameter string, separates the individual parameters
    and detects their type.

    Possible parameter types are:

    Name      | short  | example
    ----------------------------
     Integer  | i      | -374
     Float    | f      | 234.234 23.345E-23
     String   | s      | 'Stri\'ng'
     Boolean  | b      | 0 1 True false
     Name     |        | case_sensitive | converted to string

    So say you want to parse three things, name, age and if the
    person is male or not:

    The pattern will be: %(name)s%(age)i%(male)b

    As a result, the returned dict will put the first value into
    male, second into age etc. If some argument is missing, it will
    get None as its value. This also means that all the identifiers
    in the pattern will exist in the dict, they will just have the
    value None if they were not specified by the caller.

    So if we call it with the parameters as follows:
        ("John Smith", 18)
    this will result in the following dict:
        {"name": "John Smith", "age": 18, "male": None}

    Another way of calling would be:
        ("John Smith", male=True)
    this will result in the following dict:
        {"name": "John Smith", "age": None, "male": True}

    @copyright: 2004 by Florian Festi,
                2006 by Mikko Virkkilä
    @license: GNU GPL, see COPYING for details.

Definition at line 1229 of file wikiutil160a.py.


Constructor & Destructor Documentation

Definition at line 1271 of file wikiutil160a.py.

01271 
01272     def __init__(self, pattern):
01273         #parameter_re = "([^\"',]*(\"[^\"]*\"|'[^']*')?[^\"',]*)[,)]"
01274         name = "(?P<%s>[a-zA-Z_][a-zA-Z0-9_]*)"
01275         int_re = r"(?P<int>-?\d+)"
01276         bool_re = r"(?P<bool>(([10])|([Tt]rue)|([Ff]alse)))"
01277         float_re = r"(?P<float>-?\d+\.\d+([eE][+-]?\d+)?)"
01278         string_re = (r"(?P<string>('([^']|(\'))*?')|" +
01279                                 r'("([^"]|(\"))*?"))')
01280         name_re = name % "name"
01281         name_param_re = name % "name_param"
01282 
01283         param_re = r"\s*(\s*%s\s*=\s*)?(%s|%s|%s|%s|%s)\s*(,|$)" % (
01284                    name_re, float_re, int_re, bool_re, string_re, name_param_re)
01285         self.param_re = re.compile(param_re, re.U)
01286         self._parse_pattern(pattern)


Member Function Documentation

Definition at line 1308 of file wikiutil160a.py.

01308 
01309     def __str__(self):
01310         return "%s, %s, optional:%s" % (self.param_list, self.param_dict,
01311                                         self.optional)

Definition at line 1287 of file wikiutil160a.py.

01287 
01288     def _parse_pattern(self, pattern):
01289         param_re = r"(%(?P<name>\(.*?\))?(?P<type>[ibfs]{1,3}))|\|"
01290         i = 0
01291         # TODO: Optionals aren't checked.
01292         self.optional = []
01293         named = False
01294         self.param_list = []
01295         self.param_dict = {}
01296 
01297         for match in re.finditer(param_re, pattern):
01298             if match.group() == "|":
01299                 self.optional.append(i)
01300                 continue
01301             self.param_list.append(match.group('type'))
01302             if match.group('name'):
01303                 named = True
01304                 self.param_dict[match.group('name')[1:-1]] = i
01305             elif named:
01306                 raise ValueError, "Named parameter expected"
01307             i += 1

(4, 2)

Definition at line 1312 of file wikiutil160a.py.

01312 
01313     def parse_parameters(self, input):
01314         """
01315         (4, 2)
01316         """
01317         #Default list to "None"s
01318         parameter_list = [None] * len(self.param_list)
01319         parameter_dict = {}
01320         check_list = [0] * len(self.param_list)
01321 
01322         i = 0
01323         start = 0
01324         named = False
01325         while start < len(input):
01326             match = re.match(self.param_re, input[start:])
01327             if not match:
01328                 raise ValueError, "Misformatted value"
01329             start += match.end()
01330             value = None
01331             if match.group("int"):
01332                 value = int(match.group("int"))
01333                 type = 'i'
01334             elif match.group("bool"):
01335                 value = (match.group("bool") == "1") or (match.group("bool") == "True") or (match.group("bool") == "true")
01336                 type = 'b'
01337             elif match.group("float"):
01338                 value = float(match.group("float"))
01339                 type = 'f'
01340             elif match.group("string"):
01341                 value = match.group("string")[1:-1]
01342                 type = 's'
01343             elif match.group("name_param"):
01344                 value = match.group("name_param")
01345                 type = 'n'
01346             else:
01347                 value = None
01348 
01349             parameter_list.append(value)
01350             if match.group("name"):
01351                 if not self.param_dict.has_key(match.group("name")):
01352                     raise ValueError, "Unknown parameter name '%s'" % match.group("name")
01353                 nr = self.param_dict[match.group("name")]
01354                 if check_list[nr]:
01355                     #raise ValueError, "Parameter specified twice"
01356                     #TODO: Something saner that raising an exception. This is pretty good, since it ignores it.
01357                     pass
01358                 else:
01359                     check_list[nr] = 1
01360                 parameter_dict[match.group("name")] = value
01361                 parameter_list[nr] = value
01362                 named = True
01363             elif named:
01364                 raise ValueError, "Only named parameters allowed"
01365             else:
01366                 nr = i
01367                 parameter_list[nr] = value
01368 
01369             #Let's populate and map our dictionary to what's been found
01370             for name in self.param_dict.keys():
01371                 tmp = self.param_dict[name]
01372                 parameter_dict[name]=parameter_list[tmp]
01373 
01374             i += 1
01375 
01376         return parameter_list, parameter_dict
01377 
01378 
01379 """ never used:
01380     def _check_type(value, type, format):
01381         if type == 'n' and 's' in format: # n as s
01382             return value
01383 
01384         if type in format:
01385             return value # x -> x
01386 
01387         if type == 'i':
01388             if 'f' in format:
01389                 return float(value) # i -> f
01390             elif 'b' in format:
01391                 return value # i -> b
01392         elif type == 'f':
01393             if 'b' in format:
01394                 return value  # f -> b
01395         elif type == 's':
01396             if 'b' in format:
01397                 return value.lower() != 'false' # s-> b
01398 
01399         if 's' in format: # * -> s
01400             return str(value)
01401         else:
01402             pass # XXX error
01403 
01404 def main():
01405     pattern = "%i%sf%s%ifs%(a)s|%(b)s"
01406     param = ' 4,"DI\'NG", b=retry, a="DING"'
01407 
01408     #p_list, p_dict = parse_parameters(param)
01409 
01410     print 'Pattern :', pattern
01411     print 'Param :', param
01412 
01413     P = ParameterParser(pattern)
01414     print P
01415     print P.parse_parameters(param)
01416 
01417 
01418 if __name__=="__main__":
01419     main()
01420 """


Member Data Documentation

Definition at line 1291 of file wikiutil160a.py.

Definition at line 1294 of file wikiutil160a.py.

Definition at line 1293 of file wikiutil160a.py.

Definition at line 1284 of file wikiutil160a.py.


The documentation for this class was generated from the following file: