Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes | Private Member Functions
MoinMoin.wikiutil.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
def _check_type

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}

Definition at line 2006 of file wikiutil.py.


Constructor & Destructor Documentation

def MoinMoin.wikiutil.ParameterParser.__init__ (   self,
  pattern 
)

Definition at line 2044 of file wikiutil.py.

02044 
02045     def __init__(self, pattern):
02046         # parameter_re = "([^\"',]*(\"[^\"]*\"|'[^']*')?[^\"',]*)[,)]"
02047         name = "(?P<%s>[a-zA-Z_][a-zA-Z0-9_]*)"
02048         int_re = r"(?P<int>-?\d+)"
02049         bool_re = r"(?P<bool>(([10])|([Tt]rue)|([Ff]alse)))"
02050         float_re = r"(?P<float>-?\d+\.\d+([eE][+-]?\d+)?)"
02051         string_re = (r"(?P<string>('([^']|(\'))*?')|" +
02052                                 r'("([^"]|(\"))*?"))')
02053         name_re = name % "name"
02054         name_param_re = name % "name_param"
02055 
02056         param_re = r"\s*(\s*%s\s*=\s*)?(%s|%s|%s|%s|%s)\s*(,|$)" % (
02057                    name_re, float_re, int_re, bool_re, string_re, name_param_re)
02058         self.param_re = re.compile(param_re, re.U)
02059         self._parse_pattern(pattern)


Member Function Documentation

Definition at line 2081 of file wikiutil.py.

02081 
02082     def __str__(self):
02083         return "%s, %s, optional:%s" % (self.param_list, self.param_dict,
02084                                         self.optional)

def MoinMoin.wikiutil.ParameterParser._check_type (   self,
  pvalue,
  ptype,
  format 
) [private]

Definition at line 2153 of file wikiutil.py.

02153 
02154     def _check_type(self, pvalue, ptype, format):
02155         if ptype == 'n' and 's' in format: # n as s
02156             return pvalue
02157 
02158         if ptype in format:
02159             return pvalue # x -> x
02160 
02161         if ptype == 'i':
02162             if 'f' in format:
02163                 return float(pvalue) # i -> f
02164             elif 'b' in format:
02165                 return pvalue != 0 # i -> b
02166         elif ptype == 's':
02167             if 'b' in format:
02168                 if pvalue.lower() == 'false':
02169                     return False # s-> b
02170                 elif pvalue.lower() == 'true':
02171                     return True # s-> b
02172                 else:
02173                     raise ValueError('%r does not match format %r' % (pvalue, format))
02174 
02175         if 's' in format: # * -> s
02176             return str(pvalue)
02177 
02178         raise ValueError('%r does not match format %r' % (pvalue, format))
02179 

Here is the caller graph for this function:

def MoinMoin.wikiutil.ParameterParser._parse_pattern (   self,
  pattern 
) [private]

Definition at line 2060 of file wikiutil.py.

02060 
02061     def _parse_pattern(self, pattern):
02062         param_re = r"(%(?P<name>\(.*?\))?(?P<type>[ibfs]{1,3}))|\|"
02063         i = 0
02064         # TODO: Optionals aren't checked.
02065         self.optional = []
02066         named = False
02067         self.param_list = []
02068         self.param_dict = {}
02069 
02070         for match in re.finditer(param_re, pattern):
02071             if match.group() == "|":
02072                 self.optional.append(i)
02073                 continue
02074             self.param_list.append(match.group('type'))
02075             if match.group('name'):
02076                 named = True
02077                 self.param_dict[match.group('name')[1:-1]] = i
02078             elif named:
02079                 raise ValueError("Named parameter expected")
02080             i += 1

Definition at line 2085 of file wikiutil.py.

02085 
02086     def parse_parameters(self, params):
02087         # Default list/dict entries to None
02088         parameter_list = [None] * len(self.param_list)
02089         parameter_dict = dict([(key, None) for key in self.param_dict])
02090         check_list = [0] * len(self.param_list)
02091 
02092         i = 0
02093         start = 0
02094         fixed_count = 0
02095         named = False
02096 
02097         while start < len(params):
02098             match = re.match(self.param_re, params[start:])
02099             if not match:
02100                 raise ValueError("malformed parameters")
02101             start += match.end()
02102             if match.group("int"):
02103                 pvalue = int(match.group("int"))
02104                 ptype = 'i'
02105             elif match.group("bool"):
02106                 pvalue = (match.group("bool") == "1") or (match.group("bool") == "True") or (match.group("bool") == "true")
02107                 ptype = 'b'
02108             elif match.group("float"):
02109                 pvalue = float(match.group("float"))
02110                 ptype = 'f'
02111             elif match.group("string"):
02112                 pvalue = match.group("string")[1:-1]
02113                 ptype = 's'
02114             elif match.group("name_param"):
02115                 pvalue = match.group("name_param")
02116                 ptype = 'n'
02117             else:
02118                 raise ValueError("Parameter parser code does not fit param_re regex")
02119 
02120             name = match.group("name")
02121             if name:
02122                 if name not in self.param_dict:
02123                     # TODO we should think on inheritance of parameters
02124                     raise ValueError("unknown parameter name '%s'" % name)
02125                 nr = self.param_dict[name]
02126                 if check_list[nr]:
02127                     raise ValueError("parameter '%s' specified twice" % name)
02128                 else:
02129                     check_list[nr] = 1
02130                 pvalue = self._check_type(pvalue, ptype, self.param_list[nr])
02131                 parameter_dict[name] = pvalue
02132                 parameter_list[nr] = pvalue
02133                 named = True
02134             elif named:
02135                 raise ValueError("only named parameters allowed after first named parameter")
02136             else:
02137                 nr = i
02138                 if nr not in self.param_dict.values():
02139                     fixed_count = nr + 1
02140                 parameter_list[nr] = self._check_type(pvalue, ptype, self.param_list[nr])
02141 
02142             # Let's populate and map our dictionary to what's been found
02143             for name in self.param_dict:
02144                 tmp = self.param_dict[name]
02145                 parameter_dict[name] = parameter_list[tmp]
02146 
02147             i += 1
02148 
02149         for i in range(fixed_count):
02150             parameter_dict[i] = parameter_list[i]
02151 
02152         return fixed_count, parameter_dict

Here is the call graph for this function:


Member Data Documentation

Definition at line 2064 of file wikiutil.py.

Definition at line 2067 of file wikiutil.py.

Definition at line 2066 of file wikiutil.py.

Definition at line 2057 of file wikiutil.py.


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