Arity change, remove force_properties:
[tiramisu.git] / tiramisu / config.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2012-2013 Team tiramisu (see AUTHORS for all contributors)
3 #
4 # This program is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU Lesser General Public License as published by the
6 # Free Software Foundation, either version 3 of the License, or (at your
7 # option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 #
17 # The original `Config` design model is unproudly borrowed from
18 # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
19 # the whole pypy projet is under MIT licence
20 # ____________________________________________________________
21 "options handler global entry point"
22 import weakref
23 from tiramisu.error import PropertiesOptionError, ConfigError
24 from tiramisu.option import OptionDescription, Option, SymLinkOption
25 from tiramisu.setting import groups, Settings, default_encoding
26 from tiramisu.storage import get_storages, get_storage, set_storage, \
27     _impl_getstate_setting
28 from tiramisu.value import Values, Multi
29 from tiramisu.i18n import _
30
31
32 class SubConfig(object):
33     """Sub configuration management entry.
34     Tree if OptionDescription's responsability. SubConfig are generated
35     on-demand. A Config is also a SubConfig.
36     Root Config is call context below
37     """
38     __slots__ = ('_impl_context', '_impl_descr', '_impl_path')
39
40     def __init__(self, descr, context, subpath=None):
41         """ Configuration option management master class
42
43         :param descr: describes the configuration schema
44         :type descr: an instance of ``option.OptionDescription``
45         :param context: the current root config
46         :type context: `Config`
47         :type subpath: `str` with the path name
48         """
49         # main option description
50         if descr is not None and not isinstance(descr, OptionDescription):
51             raise TypeError(_('descr must be an optiondescription, not {0}'
52                               ).format(type(descr)))
53         self._impl_descr = descr
54         # sub option descriptions
55         if not isinstance(context, weakref.ReferenceType):
56             raise ValueError('context must be a Weakref')
57         self._impl_context = context
58         self._impl_path = subpath
59
60     def cfgimpl_reset_cache(self, only_expired=False, only=('values',
61                                                             'settings')):
62         "remove cache (in context)"
63         self._cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only)
64
65     def cfgimpl_get_home_by_path(self, path, force_permissive=False):
66         """:returns: tuple (config, name)"""
67         path = path.split('.')
68         for step in path[:-1]:
69             self = self.getattr(step,
70                                 force_permissive=force_permissive)
71         return self, path[-1]
72
73     def __hash__(self):
74         return hash(self.cfgimpl_get_description().impl_getkey(self))
75
76     def __eq__(self, other):
77         "Config's comparison"
78         if not isinstance(other, Config):
79             return False
80         return self.cfgimpl_get_description().impl_getkey(self) == \
81             other.cfgimpl_get_description().impl_getkey(other)
82
83     def __ne__(self, other):
84         "Config's comparison"
85         if not isinstance(other, Config):
86             return True
87         return not self == other
88
89     # ______________________________________________________________________
90     def __iter__(self):
91         """Pythonesque way of parsing group's ordered options.
92         iteration only on Options (not OptionDescriptions)"""
93         for child in self.cfgimpl_get_description().impl_getchildren():
94             if not isinstance(child, OptionDescription):
95                 try:
96                     yield child._name, getattr(self, child._name)
97                 except GeneratorExit:
98                     raise StopIteration
99                 except PropertiesOptionError:
100                     pass  # option with properties
101
102     def iter_all(self, force_permissive=False):
103         """A way of parsing options **and** groups.
104         iteration on Options and OptionDescriptions."""
105         for child in self.cfgimpl_get_description().impl_getchildren():
106             try:
107                 yield child._name, self.getattr(child._name,
108                                                 force_permissive=force_permissive)
109             except GeneratorExit:
110                 raise StopIteration
111             except PropertiesOptionError:
112                 pass  # option with properties
113
114     def iter_groups(self, group_type=None, force_permissive=False):
115         """iteration on groups objects only.
116         All groups are returned if `group_type` is `None`, otherwise the groups
117         can be filtered by categories (families, or whatever).
118
119         :param group_type: if defined, is an instance of `groups.GroupType`
120                            or `groups.MasterGroupType` that lives in
121                            `setting.groups`
122         """
123         if group_type is not None and not isinstance(group_type,
124                                                      groups.GroupType):
125             raise TypeError(_("unknown group_type: {0}").format(group_type))
126         for child in self.cfgimpl_get_description().impl_getchildren():
127             if isinstance(child, OptionDescription):
128                 try:
129                     if group_type is None or (group_type is not None and
130                                               child.impl_get_group_type()
131                                               == group_type):
132                         yield child._name, self.getattr(child._name,
133                                                         force_permissive=force_permissive)
134                 except GeneratorExit:
135                     raise StopIteration
136                 except PropertiesOptionError:
137                     pass
138     # ______________________________________________________________________
139
140     def __str__(self):
141         "Config's string representation"
142         lines = []
143         for name, grp in self.iter_groups():
144             lines.append("[{0}]".format(name))
145         for name, value in self:
146             try:
147                 lines.append("{0} = {1}".format(name, value))
148             except UnicodeEncodeError:
149                 lines.append("{0} = {1}".format(name,
150                                                 value.encode(default_encoding)))
151         return '\n'.join(lines)
152
153     __repr__ = __str__
154
155     def _cfgimpl_get_context(self):
156         """context could be None, we need to test it
157         context is None only if all reference to `Config` object is deleted
158         (for example we delete a `Config` and we manipulate a reference to
159         old `SubConfig`, `Values`, `Multi` or `Settings`)
160         """
161         context = self._impl_context()
162         if context is None:
163             raise ConfigError(_('the context does not exist anymore'))
164         return context
165
166     def cfgimpl_get_description(self):
167         if self._impl_descr is None:
168             raise ConfigError(_('no option description found for this config'
169                                 ' (may be GroupConfig)'))
170         else:
171             return self._impl_descr
172
173     def cfgimpl_get_settings(self):
174         return self._cfgimpl_get_context()._impl_settings
175
176     def cfgimpl_get_values(self):
177         return self._cfgimpl_get_context()._impl_values
178
179     # ____________________________________________________________
180     # attribute methods
181     def __setattr__(self, name, value):
182         "attribute notation mechanism for the setting of the value of an option"
183         if name.startswith('_impl_'):
184             object.__setattr__(self, name, value)
185             return
186         self._setattr(name, value)
187
188     def _setattr(self, name, value, force_permissive=False):
189         if '.' in name:
190             homeconfig, name = self.cfgimpl_get_home_by_path(name)
191             return homeconfig.__setattr__(name, value)
192         child = getattr(self.cfgimpl_get_description(), name)
193         if isinstance(child, OptionDescription):
194             raise TypeError(_("can't assign to an OptionDescription"))
195         elif not isinstance(child, SymLinkOption):
196             if self._impl_path is None:
197                 path = name
198             else:
199                 path = self._impl_path + '.' + name
200             self.cfgimpl_get_values().setitem(child, value, path,
201                                               force_permissive=force_permissive)
202         else:
203             context = self._cfgimpl_get_context()
204             path = context.cfgimpl_get_description().impl_get_path_by_opt(
205                 child._opt)
206             context._setattr(path, value, force_permissive=force_permissive)
207
208     def __delattr__(self, name):
209         child = getattr(self.cfgimpl_get_description(), name)
210         self.cfgimpl_get_values().__delitem__(child)
211
212     def __getattr__(self, name):
213         return self.getattr(name)
214
215     def _getattr(self, name, force_permissive=False, validate=True):
216         """use getattr instead of _getattr
217         """
218         return self.getattr(name, force_permissive, validate)
219
220     def getattr(self, name, force_permissive=False, validate=True):
221         """
222         attribute notation mechanism for accessing the value of an option
223         :param name: attribute name
224         :return: option's value if name is an option name, OptionDescription
225                  otherwise
226         """
227         # attribute access by passing a path,
228         # for instance getattr(self, "creole.general.family.adresse_ip_eth0")
229         if '.' in name:
230             homeconfig, name = self.cfgimpl_get_home_by_path(
231                 name, force_permissive=force_permissive)
232             return homeconfig.getattr(name, force_permissive=force_permissive,
233                                       validate=validate)
234         opt_or_descr = getattr(self.cfgimpl_get_description(), name)
235         if self._impl_path is None:
236             subpath = name
237         else:
238             subpath = self._impl_path + '.' + name
239         # symlink options
240         #FIXME a gerer plutot dans l'option ca ...
241         #FIXME je n'en sais rien en fait ... :/
242         if isinstance(opt_or_descr, SymLinkOption):
243             context = self._cfgimpl_get_context()
244             path = context.cfgimpl_get_description().impl_get_path_by_opt(
245                 opt_or_descr._opt)
246             return context.getattr(path, validate=validate,
247                                    force_permissive=force_permissive)
248         elif isinstance(opt_or_descr, OptionDescription):
249             self.cfgimpl_get_settings().validate_properties(
250                 opt_or_descr, True, False, path=subpath,
251                 force_permissive=force_permissive)
252             return SubConfig(opt_or_descr, self._impl_context, subpath)
253         else:
254             return self.cfgimpl_get_values()._get_cached_item(
255                 opt_or_descr, path=subpath,
256                 validate=validate,
257                 force_permissive=force_permissive)
258
259     def find(self, bytype=None, byname=None, byvalue=None, type_='option',
260              check_properties=True, force_permissive=False):
261         """
262             finds a list of options recursively in the config
263
264             :param bytype: Option class (BoolOption, StrOption, ...)
265             :param byname: filter by Option._name
266             :param byvalue: filter by the option's value
267             :returns: list of matching Option objects
268         """
269         return self._cfgimpl_get_context()._find(bytype, byname, byvalue,
270                                                  first=False,
271                                                  type_=type_,
272                                                  _subpath=self.cfgimpl_get_path(),
273                                                  check_properties=check_properties,
274                                                  force_permissive=force_permissive)
275
276     def find_first(self, bytype=None, byname=None, byvalue=None,
277                    type_='option', display_error=True, check_properties=True,
278                    force_permissive=False):
279         """
280             finds an option recursively in the config
281
282             :param bytype: Option class (BoolOption, StrOption, ...)
283             :param byname: filter by Option._name
284             :param byvalue: filter by the option's value
285             :returns: list of matching Option objects
286         """
287         return self._cfgimpl_get_context()._find(
288             bytype, byname, byvalue, first=True, type_=type_,
289             _subpath=self.cfgimpl_get_path(), display_error=display_error,
290             check_properties=check_properties,
291             force_permissive=force_permissive)
292
293     def _find(self, bytype, byname, byvalue, first, type_='option',
294               _subpath=None, check_properties=True, display_error=True,
295               force_permissive=False):
296         """
297         convenience method for finding an option that lives only in the subtree
298
299         :param first: return only one option if True, a list otherwise
300         :return: find list or an exception if nothing has been found
301         """
302         def _filter_by_name():
303             if byname is None or path == byname or \
304                     path.endswith('.' + byname):
305                 return True
306             return False
307
308         def _filter_by_value():
309             if byvalue is None:
310                 return True
311             try:
312                 value = self.getattr(path, force_permissive=force_permissive)
313                 if isinstance(value, Multi):
314                     return byvalue in value
315                 else:
316                     return value == byvalue
317             except PropertiesOptionError:  # a property is a restriction
318                                            # upon the access of the value
319                 return False
320
321         def _filter_by_type():
322             if bytype is None:
323                 return True
324             if isinstance(option, bytype):
325                 return True
326             return False
327
328         if type_ not in ('option', 'path', 'value'):
329             raise ValueError(_('unknown type_ type {0}'
330                                'for _find').format(type_))
331         find_results = []
332         opts, paths = self.cfgimpl_get_description()._cache_paths
333         for index in range(0, len(paths)):
334             option = opts[index]
335             if isinstance(option, OptionDescription):
336                 continue
337             path = paths[index]
338             if _subpath is not None and not path.startswith(_subpath + '.'):
339                 continue
340             if not _filter_by_name():
341                 continue
342             if not _filter_by_value():
343                 continue
344             if not _filter_by_type():
345                 continue
346             #remove option with propertyerror, ...
347             if byvalue is None and check_properties:
348                 try:
349                     value = self.getattr(path,
350                                          force_permissive=force_permissive)
351                 except PropertiesOptionError:
352                     # a property restricts the access of the value
353                     continue
354             if type_ == 'value':
355                 retval = value
356             elif type_ == 'path':
357                 retval = path
358             elif type_ == 'option':
359                 retval = option
360             if first:
361                 return retval
362             else:
363                 find_results.append(retval)
364         return self._find_return_results(find_results, display_error)
365
366     def _find_return_results(self, find_results, display_error):
367         if find_results == []:
368             if display_error:
369                 raise AttributeError(_("no option found in config"
370                                        " with these criteria"))
371             else:
372                 # translation is slow
373                 raise AttributeError()
374         else:
375             return find_results
376
377     def make_dict(self, flatten=False, _currpath=None, withoption=None,
378                   withvalue=None, force_permissive=False):
379         """exports the whole config into a `dict`, for example:
380
381         >>> print cfg.make_dict()
382         {'od2.var4': None, 'od2.var5': None, 'od2.var6': None}
383
384
385
386         :param flatten: returns a dict(name=value) instead of a dict(path=value)
387                         ::
388
389                             >>> print cfg.make_dict(flatten=True)
390                             {'var5': None, 'var4': None, 'var6': None}
391
392         :param withoption: returns the options that are present in the very same
393                            `OptionDescription` than the `withoption` itself::
394
395                                 >>> print cfg.make_dict(withoption='var1')
396                                 {'od2.var4': None, 'od2.var5': None,
397                                 'od2.var6': None,
398                                 'od2.var1': u'value',
399                                 'od1.var1': None,
400                                 'od1.var3': None,
401                                 'od1.var2': None}
402
403         :param withvalue: returns the options that have the value `withvalue`
404                           ::
405
406                             >>> print c.make_dict(withoption='var1',
407                                                   withvalue=u'value')
408                             {'od2.var4': None,
409                             'od2.var5': None,
410                             'od2.var6': None,
411                             'od2.var1': u'value'}
412
413         :returns: dict of Option's name (or path) and values
414         """
415         pathsvalues = []
416         if _currpath is None:
417             _currpath = []
418         if withoption is None and withvalue is not None:
419             raise ValueError(_("make_dict can't filtering with value without "
420                                "option"))
421         if withoption is not None:
422             mypath = self.cfgimpl_get_path()
423             for path in self._cfgimpl_get_context()._find(bytype=Option,
424                                                           byname=withoption,
425                                                           byvalue=withvalue,
426                                                           first=False,
427                                                           type_='path',
428                                                           _subpath=mypath,
429                                                           force_permissive=force_permissive):
430                 path = '.'.join(path.split('.')[:-1])
431                 opt = self._cfgimpl_get_context().cfgimpl_get_description(
432                 ).impl_get_opt_by_path(path)
433                 if mypath is not None:
434                     if mypath == path:
435                         withoption = None
436                         withvalue = None
437                         break
438                     else:
439                         tmypath = mypath + '.'
440                         if not path.startswith(tmypath):
441                             raise AttributeError(_('unexpected path {0}, '
442                                                    'should start with {1}'
443                                                    '').format(path, mypath))
444                         path = path[len(tmypath):]
445                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
446                                     force_permissive=force_permissive)
447         #withoption can be set to None below !
448         if withoption is None:
449             for opt in self.cfgimpl_get_description().impl_getchildren():
450                 path = opt._name
451                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten,
452                                     force_permissive=force_permissive)
453         if _currpath == []:
454             options = dict(pathsvalues)
455             return options
456         return pathsvalues
457
458     def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten,
459                        force_permissive=False):
460         try:
461             if isinstance(opt, OptionDescription):
462                 pathsvalues += self.getattr(path,
463                                             force_permissive=force_permissive).make_dict(
464                                                 flatten,
465                                                 _currpath + path.split('.'),
466                                                 force_permissive=force_permissive)
467             else:
468                 value = self.getattr(opt._name,
469                                      force_permissive=force_permissive)
470                 if flatten:
471                     name = opt._name
472                 else:
473                     name = '.'.join(_currpath + [opt._name])
474                 pathsvalues.append((name, value))
475         except PropertiesOptionError:
476             pass
477
478     def cfgimpl_get_path(self):
479         descr = self.cfgimpl_get_description()
480         context_descr = self._cfgimpl_get_context().cfgimpl_get_description()
481         return context_descr.impl_get_path_by_opt(descr)
482
483
484 class _CommonConfig(SubConfig):
485     "abstract base class for the Config, GroupConfig and the MetaConfig"
486     __slots__ = ('_impl_values', '_impl_settings', '_impl_meta', '_impl_test')
487
488     def _impl_build_all_paths(self):
489         self.cfgimpl_get_description().impl_build_cache()
490
491     def read_only(self):
492         "read only is a global config's setting, see `settings.py`"
493         self.cfgimpl_get_settings().read_only()
494
495     def read_write(self):
496         "read write is a global config's setting, see `settings.py`"
497         self.cfgimpl_get_settings().read_write()
498
499     def getowner(self, opt, force_permissive=False):
500         """convenience method to retrieve an option's owner
501         from the config itself
502         """
503         if not isinstance(opt, Option) and not isinstance(opt, SymLinkOption):
504             raise TypeError(_('opt in getowner must be an option not {0}'
505                               '').format(type(opt)))
506         return self.cfgimpl_get_values().getowner(opt,
507                                                   force_permissive=force_permissive)
508
509     def unwrap_from_path(self, path, force_permissive=False):
510         """convenience method to extract and Option() object from the Config()
511         and it is **fast**: finds the option directly in the appropriate
512         namespace
513
514         :returns: Option()
515         """
516         if '.' in path:
517             homeconfig, path = self.cfgimpl_get_home_by_path(
518                 path, force_permissive=force_permissive)
519             return getattr(homeconfig.cfgimpl_get_description(), path)
520         return getattr(self.cfgimpl_get_description(), path)
521
522     def cfgimpl_get_path(self):
523         return None
524
525     def cfgimpl_get_meta(self):
526         if self._impl_meta is not None:
527             return self._impl_meta()
528
529     # information
530     def impl_set_information(self, key, value):
531         """updates the information's attribute
532
533         :param key: information's key (ex: "help", "doc"
534         :param value: information's value (ex: "the help string")
535         """
536         self._impl_values.set_information(key, value)
537
538     def impl_get_information(self, key, default=None):
539         """retrieves one information's item
540
541         :param key: the item string (ex: "help")
542         """
543         return self._impl_values.get_information(key, default)
544
545     # ----- state
546     def __getstate__(self):
547         if self._impl_meta is not None:
548             raise ConfigError(_('cannot serialize Config with MetaConfig'))
549         slots = set()
550         for subclass in self.__class__.__mro__:
551             if subclass is not object:
552                 slots.update(subclass.__slots__)
553         slots -= frozenset(['_impl_context', '_impl_meta', '__weakref__'])
554         state = {}
555         for slot in slots:
556             try:
557                 state[slot] = getattr(self, slot)
558             except AttributeError:
559                 pass
560         storage = self._impl_values._p_._storage
561         if not storage.serializable:
562             raise ConfigError(_('this storage is not serialisable, could be a '
563                               'none persistent storage'))
564         state['_storage'] = {'session_id': storage.session_id,
565                              'persistent': storage.persistent}
566         state['_impl_setting'] = _impl_getstate_setting()
567         return state
568
569     def __setstate__(self, state):
570         for key, value in state.items():
571             if key not in ['_storage', '_impl_setting']:
572                 setattr(self, key, value)
573         set_storage(**state['_impl_setting'])
574         self._impl_context = weakref.ref(self)
575         self._impl_settings.context = weakref.ref(self)
576         self._impl_values.context = weakref.ref(self)
577         storage = get_storage(test=self._impl_test, **state['_storage'])
578         self._impl_values._impl_setstate(storage)
579         self._impl_settings._impl_setstate(storage)
580         self._impl_meta = None
581
582
583 # ____________________________________________________________
584 class Config(_CommonConfig):
585     "main configuration management entry"
586     __slots__ = ('__weakref__',)
587
588     def __init__(self, descr, session_id=None, persistent=False):
589         """ Configuration option management master class
590
591         :param descr: describes the configuration schema
592         :type descr: an instance of ``option.OptionDescription``
593         :param context: the current root config
594         :type context: `Config`
595         :param session_id: session ID is import with persistent Config to
596         retrieve good session
597         :type session_id: `str`
598         :param persistent: if persistent, don't delete storage when leaving
599         :type persistent: `boolean`
600         """
601         settings, values = get_storages(self, session_id, persistent)
602         self._impl_settings = Settings(self, settings)
603         self._impl_values = Values(self, values)
604         super(Config, self).__init__(descr, weakref.ref(self))
605         self._impl_build_all_paths()
606         self._impl_meta = None
607         #undocumented option used only in test script
608         self._impl_test = False
609
610     def cfgimpl_reset_cache(self,
611                             only_expired=False,
612                             only=('values', 'settings')):
613         if 'values' in only:
614             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
615         if 'settings' in only:
616             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
617
618
619 class GroupConfig(_CommonConfig):
620     __slots__ = ('_impl_children', '__weakref__')
621
622     def __init__(self, children, session_id=None, persistent=False,
623                  _descr=None):
624         if not isinstance(children, list):
625             raise ValueError(_("metaconfig's children must be a list"))
626         self._impl_children = children
627         settings, values = get_storages(self, session_id, persistent)
628         self._impl_settings = Settings(self, settings)
629         self._impl_values = Values(self, values)
630         super(GroupConfig, self).__init__(_descr, weakref.ref(self))
631         self._impl_meta = None
632         #undocumented option used only in test script
633         self._impl_test = False
634
635     def cfgimpl_get_children(self):
636         return self._impl_children
637
638     #def cfgimpl_get_context(self):
639     #    "a meta config is a config which has a setting, that is itself"
640     #    return self
641     #
642     def cfgimpl_reset_cache(self,
643                             only_expired=False,
644                             only=('values', 'settings')):
645         if 'values' in only:
646             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
647         if 'settings' in only:
648             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
649         for child in self._impl_children:
650             child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
651
652     def setattrs(self, path, value):
653         """Setattr not in current GroupConfig, but in each children
654         """
655         for child in self._impl_children:
656             try:
657                 if not isinstance(child, GroupConfig):
658                     setattr(child, path, value)
659                 else:
660                     child.setattrs(path, value)
661             except PropertiesOptionError:
662                 pass
663
664     def find_firsts(self, byname=None, bypath=None, byvalue=None,
665                     type_='path', display_error=True):
666         """Find first not in current GroupConfig, but in each children
667         """
668         ret = []
669         #if MetaConfig, all children have same OptionDescription as context
670         #so search only one time for all children
671         try:
672             if bypath is None and byname is not None and \
673                     isinstance(self, MetaConfig):
674                 bypath = self._find(bytype=None, byvalue=None, byname=byname,
675                                     first=True, type_='path',
676                                     check_properties=False,
677                                     display_error=display_error)
678                 byname = None
679         except AttributeError:
680             pass
681         for child in self._impl_children:
682             try:
683                 if not isinstance(child, MetaConfig):
684                     if bypath is not None:
685                         #if byvalue is None, try if not raise
686                         value = getattr(child, bypath)
687                         if byvalue is not None:
688                             if isinstance(value, Multi):
689                                 if byvalue in value:
690                                     ret.append(child)
691                             else:
692                                 if value == byvalue:
693                                     ret.append(child)
694                         else:
695                             ret.append(child)
696                     else:
697                         ret.append(child.find_first(byname=byname,
698                                                     byvalue=byvalue,
699                                                     type_=type_,
700                                                     display_error=False))
701                 else:
702                     ret.extend(child.find_firsts(byname=byname,
703                                                  bypath=bypath,
704                                                  byvalue=byvalue,
705                                                  type_=type_,
706                                                  display_error=False))
707             except AttributeError:
708                 pass
709         return self._find_return_results(ret, display_error)
710
711
712 class MetaConfig(GroupConfig):
713     __slots__ = tuple()
714
715     def __init__(self, children, session_id=None, persistent=False):
716         descr = None
717         for child in children:
718             if not isinstance(child, _CommonConfig):
719                 raise TypeError(_("metaconfig's children "
720                                   "should be config, not {0}"
721                                   ).format(type(child)))
722             if child.cfgimpl_get_meta() is not None:
723                 raise ValueError(_("child has already a metaconfig's"))
724             if descr is None:
725                 descr = child.cfgimpl_get_description()
726             elif not descr is child.cfgimpl_get_description():
727                 raise ValueError(_('all config in metaconfig must '
728                                    'have the same optiondescription'))
729             child._impl_meta = weakref.ref(self)
730
731         super(MetaConfig, self).__init__(children, session_id, persistent, descr)
732
733
734 def mandatory_warnings(config):
735     #only for retro-compatibility
736     return config.cfgimpl_get_values().mandatory_warnings()