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