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