Merge branch '_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, force_permissive=False):
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                                                   force_permissive=force_permissive)
515
516     def unwrap_from_path(self, path, force_permissive=False):
517         """convenience method to extract and Option() object from the Config()
518         and it is **fast**: finds the option directly in the appropriate
519         namespace
520
521         :returns: Option()
522         """
523         if '.' in path:
524             homeconfig, path = self.cfgimpl_get_home_by_path(
525                 path, force_permissive=force_permissive)
526             return getattr(homeconfig.cfgimpl_get_description(), path)
527         return getattr(self.cfgimpl_get_description(), path)
528
529     def cfgimpl_get_path(self):
530         return None
531
532     def cfgimpl_get_meta(self):
533         if self._impl_meta is not None:
534             return self._impl_meta()
535
536     # information
537     def impl_set_information(self, key, value):
538         """updates the information's attribute
539
540         :param key: information's key (ex: "help", "doc"
541         :param value: information's value (ex: "the help string")
542         """
543         self._impl_values.set_information(key, value)
544
545     def impl_get_information(self, key, default=None):
546         """retrieves one information's item
547
548         :param key: the item string (ex: "help")
549         """
550         return self._impl_values.get_information(key, default)
551
552     # ----- state
553     def __getstate__(self):
554         if self._impl_meta is not None:
555             raise ConfigError(_('cannot serialize Config with MetaConfig'))
556         slots = set()
557         for subclass in self.__class__.__mro__:
558             if subclass is not object:
559                 slots.update(subclass.__slots__)
560         slots -= frozenset(['_impl_context', '_impl_meta', '__weakref__'])
561         state = {}
562         for slot in slots:
563             try:
564                 state[slot] = getattr(self, slot)
565             except AttributeError:
566                 pass
567         storage = self._impl_values._p_._storage
568         if not storage.serializable:
569             raise ConfigError(_('this storage is not serialisable, could be a '
570                               'none persistent storage'))
571         state['_storage'] = {'session_id': storage.session_id,
572                              'persistent': storage.persistent}
573         state['_impl_setting'] = _impl_getstate_setting()
574         return state
575
576     def __setstate__(self, state):
577         for key, value in state.items():
578             if key not in ['_storage', '_impl_setting']:
579                 setattr(self, key, value)
580         set_storage(**state['_impl_setting'])
581         self._impl_context = weakref.ref(self)
582         self._impl_settings.context = weakref.ref(self)
583         self._impl_values.context = weakref.ref(self)
584         storage = get_storage(test=self._impl_test, **state['_storage'])
585         self._impl_values._impl_setstate(storage)
586         self._impl_settings._impl_setstate(storage)
587         self._impl_meta = None
588
589
590 # ____________________________________________________________
591 class Config(_CommonConfig):
592     "main configuration management entry"
593     __slots__ = ('__weakref__',)
594
595     def __init__(self, descr, session_id=None, persistent=False):
596         """ Configuration option management master class
597
598         :param descr: describes the configuration schema
599         :type descr: an instance of ``option.OptionDescription``
600         :param context: the current root config
601         :type context: `Config`
602         :param session_id: session ID is import with persistent Config to
603         retrieve good session
604         :type session_id: `str`
605         :param persistent: if persistent, don't delete storage when leaving
606         :type persistent: `boolean`
607         """
608         settings, values = get_storages(self, session_id, persistent)
609         self._impl_settings = Settings(self, settings)
610         self._impl_values = Values(self, values)
611         super(Config, self).__init__(descr, weakref.ref(self))
612         self._impl_build_all_paths()
613         self._impl_meta = None
614         #undocumented option used only in test script
615         self._impl_test = False
616
617     def cfgimpl_reset_cache(self,
618                             only_expired=False,
619                             only=('values', 'settings')):
620         if 'values' in only:
621             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
622         if 'settings' in only:
623             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
624
625
626 class GroupConfig(_CommonConfig):
627     __slots__ = ('_impl_children', '__weakref__')
628
629     def __init__(self, children, session_id=None, persistent=False,
630                  _descr=None):
631         if not isinstance(children, list):
632             raise ValueError(_("metaconfig's children must be a list"))
633         self._impl_children = children
634         settings, values = get_storages(self, session_id, persistent)
635         self._impl_settings = Settings(self, settings)
636         self._impl_values = Values(self, values)
637         super(GroupConfig, self).__init__(_descr, weakref.ref(self))
638         self._impl_meta = None
639         #undocumented option used only in test script
640         self._impl_test = False
641
642     def cfgimpl_get_children(self):
643         return self._impl_children
644
645     #def cfgimpl_get_context(self):
646     #    "a meta config is a config which has a setting, that is itself"
647     #    return self
648     #
649     def cfgimpl_reset_cache(self,
650                             only_expired=False,
651                             only=('values', 'settings')):
652         if 'values' in only:
653             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
654         if 'settings' in only:
655             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
656         for child in self._impl_children:
657             child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
658
659     def setattrs(self, path, value):
660         """Setattr not in current GroupConfig, but in each children
661         """
662         for child in self._impl_children:
663             try:
664                 if not isinstance(child, GroupConfig):
665                     setattr(child, path, value)
666                 else:
667                     child.setattrs(path, value)
668             except PropertiesOptionError:
669                 pass
670
671     def find_firsts(self, byname=None, bypath=None, byvalue=None,
672                     type_='path', display_error=True):
673         """Find first not in current GroupConfig, but in each children
674         """
675         ret = []
676         #if MetaConfig, all children have same OptionDescription as context
677         #so search only one time for all children
678         try:
679             if bypath is None and byname is not None and \
680                     isinstance(self, MetaConfig):
681                 bypath = self._find(bytype=None, byvalue=None, byname=byname,
682                                     first=True, type_='path',
683                                     check_properties=False,
684                                     display_error=display_error)
685                 byname = None
686         except AttributeError:
687             pass
688         for child in self._impl_children:
689             try:
690                 if not isinstance(child, MetaConfig):
691                     if bypath is not None:
692                         #if byvalue is None, try if not raise
693                         value = getattr(child, bypath)
694                         if byvalue is not None:
695                             if isinstance(value, Multi):
696                                 if byvalue in value:
697                                     ret.append(child)
698                             else:
699                                 if value == byvalue:
700                                     ret.append(child)
701                         else:
702                             ret.append(child)
703                     else:
704                         ret.append(child.find_first(byname=byname,
705                                                     byvalue=byvalue,
706                                                     type_=type_,
707                                                     display_error=False))
708                 else:
709                     ret.extend(child.find_firsts(byname=byname,
710                                                  bypath=bypath,
711                                                  byvalue=byvalue,
712                                                  type_=type_,
713                                                  display_error=False))
714             except AttributeError:
715                 pass
716         return self._find_return_results(ret, display_error)
717
718
719 class MetaConfig(GroupConfig):
720     __slots__ = tuple()
721
722     def __init__(self, children, session_id=None, persistent=False):
723         descr = None
724         for child in children:
725             if not isinstance(child, _CommonConfig):
726                 raise TypeError(_("metaconfig's children "
727                                   "should be config, not {0}"
728                                   ).format(type(child)))
729             if child.cfgimpl_get_meta() is not None:
730                 raise ValueError(_("child has already a metaconfig's"))
731             if descr is None:
732                 descr = child.cfgimpl_get_description()
733             elif not descr is child.cfgimpl_get_description():
734                 raise ValueError(_('all config in metaconfig must '
735                                    'have the same optiondescription'))
736             child._impl_meta = weakref.ref(self)
737
738         super(MetaConfig, self).__init__(children, session_id, persistent, descr)
739
740
741 def mandatory_warnings(config):
742     #only for retro-compatibility
743     return config.cfgimpl_get_values().mandatory_warnings()