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