2e0deb382db2d79b3e4863bcc699bb34b679efc1
[tiramisu.git] / tiramisu / value.py
1 # -*- coding: utf-8 -*-
2 "takes care of the option's values and multi values"
3 # Copyright (C) 2013-2014 Team tiramisu (see AUTHORS for all contributors)
4 #
5 # This program is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as published by the
7 # Free Software Foundation, either version 3 of the License, or (at your
8 # option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
13 # details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 # ____________________________________________________________
18 from time import time
19 import sys
20 import weakref
21 from tiramisu.error import ConfigError, SlaveError, PropertiesOptionError
22 from tiramisu.setting import owners, expires_time, undefined
23 from tiramisu.autolib import carry_out_calculation
24 from tiramisu.i18n import _
25 from tiramisu.option import SymLinkOption, DynSymLinkOption, Option
26
27
28 class Values(object):
29     """The `Config`'s root is indeed  in charge of the `Option()`'s values,
30     but the values are physicaly located here, in `Values`, wich is also
31     responsible of a caching utility.
32     """
33     __slots__ = ('context', '_p_', '__weakref__')
34
35     def __init__(self, context, storage):
36         """
37         Initializes the values's dict.
38
39         :param context: the context is the home config's values
40
41         """
42         self.context = weakref.ref(context)
43         # the storage type is dictionary or sqlite3
44         self._p_ = storage
45
46     def _getcontext(self):
47         """context could be None, we need to test it
48         context is None only if all reference to `Config` object is deleted
49         (for example we delete a `Config` and we manipulate a reference to
50         old `SubConfig`, `Values`, `Multi` or `Settings`)
51         """
52         context = self.context()
53         if context is None:  # pragma: optional cover
54             raise ConfigError(_('the context does not exist anymore'))
55         return context
56
57     def _get_multi(self, opt, path):
58         return Multi([], self.context, opt, path)
59
60     def _getdefaultvalue(self, opt, path, with_meta, index, submulti_index):
61         # if value has callback and is not set
62         if opt.impl_has_callback():
63             callback, callback_params = opt.impl_get_callback()
64             value = carry_out_calculation(opt, context=self._getcontext(),
65                                           callback=callback,
66                                           callback_params=callback_params,
67                                           index=index)
68             if isinstance(value, list) and index is not undefined:
69                 #if return a list and index is set, return value only if
70                 #it's a submulti without submulti_index and without list of list
71                 if opt.impl_is_submulti() and submulti_index is undefined and \
72                         (len(value) == 0 or not isinstance(value[0], list)):
73                     return value
74             else:
75                 return value
76         if with_meta:
77             meta = self._getcontext().cfgimpl_get_meta()
78             if meta is not None:
79                 try:
80                     value = meta.cfgimpl_get_values(
81                     )._get_cached_item(opt, path)
82                     if isinstance(value, Multi):
83                         if index is not undefined:
84                             value = value[index]
85                         else:
86                             value = list(value)
87                     return value
88                 except PropertiesOptionError:
89                     pass
90         # now try to get default value
91         value = opt.impl_getdefault()
92         if opt.impl_is_multi() and index is not undefined:
93             if value == []:
94                 value = opt.impl_getdefault_multi()
95             else:
96                 try:
97                     value = value[index]
98                 except IndexError:
99                     value = opt.impl_getdefault_multi()
100         return value
101
102     def _getvalue(self, opt, path, is_default, self_properties,
103                   index=undefined, submulti_index=undefined, with_meta=True,
104                   masterlen=undefined):
105         """actually retrieves the value
106
107         :param opt: the `option.Option()` object
108         :returns: the option's value (or the default value if not set)
109         """
110         force_default = 'frozen' in self_properties and \
111             'force_default_on_freeze' in self_properties
112         # not default value
113         if not is_default and not force_default:
114             if opt.impl_is_master_slaves('slave'):
115                 return self._p_.getvalue(path, index)
116             else:
117                 value = self._p_.getvalue(path)
118                 if index is not undefined:
119                     try:
120                         return value[index]
121                     except IndexError:
122                         #value is smaller than expected
123                         #so return default value
124                         pass
125                 else:
126                     return value
127         return self._getdefaultvalue(opt, path, with_meta, index, submulti_index)
128
129     def get_modified_values(self):
130         context = self._getcontext()
131         if context._impl_descr is not None:
132             for opt, path in context.cfgimpl_get_description(
133             )._get_force_store_value():
134                 self._getowner(opt, path, force_permissive=True)
135         return self._p_.get_modified_values()
136
137     def __contains__(self, opt):
138         """
139         implements the 'in' keyword syntax in order provide a pythonic way
140         to kow if an option have a value
141
142         :param opt: the `option.Option()` object
143         """
144         path = opt.impl_getpath(self._getcontext())
145         return self._contains(path)
146
147     def _contains(self, path):
148         return self._p_.hasvalue(path)
149
150     def __delitem__(self, opt):
151         """overrides the builtins `del()` instructions"""
152         self.reset(opt)
153
154     def reset(self, opt, path=None, validate=True):
155         if path is None:
156             path = opt.impl_getpath(self._getcontext())
157         context = self._getcontext()
158         if validate:
159             context.cfgimpl_get_settings().validate_properties(opt, False,
160                                                                True, path)
161
162         hasvalue = self._contains(path)
163
164         setting = context.cfgimpl_get_settings()
165         setting_properties = setting._getproperties(read_write=False)
166         if 'validator' in setting_properties and validate and hasvalue:
167             fake_context = context._gen_fake_values()
168             fake_value = fake_context.cfgimpl_get_values()
169             fake_value.reset(opt, path, validate=False)
170             opt.impl_validate(getattr(fake_context, path),
171                               fake_context, 'validator' in setting_properties)
172         context.cfgimpl_reset_cache()
173         if opt.impl_is_master_slaves('master'):
174             opt.impl_get_master_slaves().reset(opt, self)
175         if hasvalue:
176             self._p_.resetvalue(path)
177
178     def _isempty(self, opt, value, force_allow_empty_list=False, index=None):
179         "convenience method to know if an option is empty"
180         if value is undefined:
181             return False
182         else:
183             empty = opt._empty
184             if index in [None, undefined] and opt.impl_is_multi():
185                 if force_allow_empty_list:
186                     allow_empty_list = True
187                 else:
188                     allow_empty_list = opt.impl_allow_empty_list()
189                     if allow_empty_list is undefined:
190                         if opt.impl_is_master_slaves('slave'):
191                             allow_empty_list = True
192                         else:
193                             allow_empty_list = False
194                 isempty = (not allow_empty_list and value == []) or \
195                     None in value or empty in value
196             else:
197                 isempty = value is None or value == empty
198         return isempty
199
200     def __getitem__(self, opt):
201         "enables us to use the pythonic dictionary-like access to values"
202         return self.getitem(opt)
203
204     def getitem(self, opt, validate=True, force_permissive=False):
205         """
206         """
207         return self._get_cached_item(opt, validate=validate,
208                                      force_permissive=force_permissive)
209
210     def _get_cached_item(self, opt, path=None, validate=True,
211                          force_permissive=False, force_properties=None,
212                          validate_properties=True,
213                          setting_properties=undefined, self_properties=undefined):
214         untrusted_cached_properties = force_properties is None
215         context = self._getcontext()
216         if path is None:
217             path = opt.impl_getpath(context)
218         ntime = None
219         if setting_properties is undefined:
220             setting_properties = context.cfgimpl_get_settings(
221             )._getproperties(read_write=False)
222         if self_properties is undefined:
223             self_properties = context.cfgimpl_get_settings()._getproperties(
224                 opt, path, read_write=False, setting_properties=setting_properties)
225         if 'cache' in setting_properties and self._p_.hascache(path):
226             if 'expire' in setting_properties:
227                 ntime = int(time())
228             is_cached, value = self._p_.getcache(path, ntime)
229             if is_cached:
230                 if opt.impl_is_multi() and not isinstance(value, Multi):
231                     value = Multi(value, self.context, opt, path)
232                 if not untrusted_cached_properties:
233                     # revalidate properties (because not default properties)
234                     context.cfgimpl_get_settings().validate_properties(opt, False, False, value=value,
235                                                                        path=path,
236                                                                        force_permissive=force_permissive,
237                                                                        force_properties=force_properties,
238                                                                        setting_properties=setting_properties,
239                                                                        self_properties=self_properties)
240                 return value
241         val = self._getitem(opt, path, validate, force_permissive,
242                             force_properties, validate_properties,
243                             setting_properties, self_properties=self_properties)
244         if 'cache' in setting_properties and validate and validate_properties \
245                 and force_permissive is False and force_properties is None:
246             if 'expire' in setting_properties:
247                 if ntime is None:
248                     ntime = int(time())
249                 ntime = ntime + expires_time
250             self._p_.setcache(path, val, ntime)
251         return val
252
253     def _getitem(self, opt, path, validate, force_permissive, force_properties,
254                  validate_properties, setting_properties=undefined,
255                  self_properties=undefined):
256         if opt.impl_is_master_slaves():
257             return opt.impl_get_master_slaves().getitem(self, opt, path,
258                                                         validate,
259                                                         force_permissive,
260                                                         force_properties,
261                                                         validate_properties,
262                                                         setting_properties=setting_properties,
263                                                         self_properties=self_properties)
264         else:
265             return self._get_validated_value(opt, path, validate,
266                                              force_permissive,
267                                              force_properties,
268                                              validate_properties,
269                                              setting_properties=setting_properties,
270                                              self_properties=self_properties)
271
272     def _get_validated_value(self, opt, path, validate, force_permissive,
273                              force_properties, validate_properties,
274                              index=undefined, submulti_index=undefined,
275                              with_meta=True, setting_properties=undefined,
276                              self_properties=undefined, masterlen=undefined):
277         """same has getitem but don't touch the cache
278         index is None for slave value, if value returned is not a list, just return []
279         """
280         context = self._getcontext()
281         setting = context.cfgimpl_get_settings()
282         if setting_properties is undefined:
283             setting_properties = setting._getproperties(read_write=False)
284         if self_properties is undefined:
285             self_properties = setting._getproperties(opt, path, read_write=False)
286         is_default = self._is_default_owner(opt, path,
287                                             validate_properties=False,
288                                             validate_meta=False,
289                                             self_properties=self_properties,
290                                             index=index)
291         try:
292             value = self._getvalue(opt, path, is_default, self_properties,
293                                    index=index, submulti_index=submulti_index,
294                                    with_meta=with_meta,
295                                    masterlen=masterlen)
296             config_error = None
297         except ConfigError as err:
298             # For calculating properties, we need value (ie for mandatory
299             # value).
300             # If value is calculating with a PropertiesOptionError's option
301             # _getvalue raise a ConfigError.
302             # We can not raise ConfigError if this option should raise
303             # PropertiesOptionError too. So we get config_error and raise
304             # ConfigError if properties did not raise.
305             # cannot assign config_err directly in python 3.3
306             config_error = err
307             # value is not set, for 'undefined' (cannot set None because of
308             # mandatory property)
309             value = undefined
310         else:
311             if index is undefined:
312                 force_index = None
313             else:
314                 force_index = index
315             if opt.impl_is_multi():
316                 if force_index is None:
317                     value = Multi(value, self.context, opt, path)
318                 elif opt.impl_is_submulti() and submulti_index is undefined:
319                     value = SubMulti(value, self.context, opt, path,
320                                      force_index)
321
322             if validate:
323                 if submulti_index is undefined:
324                     force_submulti_index = None
325                 else:
326                     force_submulti_index = submulti_index
327                 try:
328                     opt.impl_validate(value, context,
329                                       'validator' in setting_properties,
330                                       force_index=force_index,
331                                       force_submulti_index=force_submulti_index)
332                 except ValueError, err:
333                     config_error = err
334                     value = None
335
336             if is_default and 'force_store_value' in self_properties:
337                 if isinstance(value, Multi):
338                     item = list(value)
339                 else:
340                     item = value
341                 self.setitem(opt, item, path, is_write=False,
342                              force_permissive=force_permissive)
343         if validate_properties:
344             if config_error is not None:
345                 # should not raise PropertiesOptionError if option is
346                 # mandatory
347                 val_props = undefined
348             else:
349                 val_props = value
350             setting.validate_properties(opt, False, False, value=val_props,
351                                         path=path,
352                                         force_permissive=force_permissive,
353                                         force_properties=force_properties,
354                                         setting_properties=setting_properties,
355                                         self_properties=self_properties,
356                                         index=index)
357         if config_error is not None:
358             raise config_error
359         return value
360
361     def __setitem__(self, opt, value):  # pragma: optional cover
362         raise ConfigError(_('you should only set value with config'))
363
364     def setitem(self, opt, value, path, force_permissive=False,
365                 is_write=True):
366         # is_write is, for example, used with "force_store_value"
367         # user didn't change value, so not write
368         # valid opt
369         context = self._getcontext()
370         setting_properties = context.cfgimpl_get_settings()._getproperties(read_write=False)
371         if 'validator' in setting_properties:
372             fake_context = context._gen_fake_values()
373             fake_context.cfgimpl_get_values()._setitem(opt, value, path,
374                                                        force_permissive,
375                                                        is_write,
376                                                        setting_properties)
377             opt.impl_validate(value, fake_context)
378         self._setitem(opt, value, path, force_permissive, is_write,
379                       setting_properties, validate_properties=False)
380
381     def _setitem(self, opt, value, path, force_permissive, is_write,
382                  setting_properties, validate_properties=True):
383         if opt.impl_is_master_slaves():
384             opt.impl_get_master_slaves().setitem(self, opt, value, path)
385         self._setvalue(opt, path, value, force_permissive=force_permissive,
386                        is_write=is_write,
387                        setting_properties=setting_properties,
388                        validate_properties=validate_properties)
389
390     def _setvalue(self, opt, path, value, force_permissive=False,
391                   is_write=True, validate_properties=True,
392                   setting_properties=undefined, index=None):
393         context = self._getcontext()
394         context.cfgimpl_reset_cache()
395         if validate_properties:
396             setting = context.cfgimpl_get_settings()
397             setting.validate_properties(opt, False, is_write,
398                                         value=value, path=path,
399                                         force_permissive=force_permissive,
400                                         setting_properties=setting_properties)
401         if isinstance(value, Multi):
402             value = list(value)
403             if opt.impl_is_submulti():
404                 for idx, val in enumerate(value):
405                     if isinstance(val, SubMulti):
406                         value[idx] = list(val)
407         owner = context.cfgimpl_get_settings().getowner()
408         if opt.impl_is_master_slaves('slave') and index is None:
409             try:
410                 self._p_.resetvalue(path)
411             except ValueError:
412                 pass
413             for idx, val in enumerate(value):
414                 self._p_.setvalue(path, val, owner, idx)
415         else:
416             self._p_.setvalue(path, value, owner, index)
417
418     def _is_meta(self, opt, path):
419         context = self._getcontext()
420         setting = context.cfgimpl_get_settings()
421         self_properties = setting._getproperties(opt, path, read_write=False)
422         if 'frozen' in self_properties and 'force_default_on_freeze' in self_properties:
423             return False
424         if self._p_.getowner(path, owners.default, only_default=True) is not owners.default:
425             return False
426         if context.cfgimpl_get_meta() is not None:
427             return True
428         return False
429
430     def getowner(self, opt, index=None, force_permissive=False):
431         """
432         retrieves the option's owner
433
434         :param opt: the `option.Option` object
435         :param force_permissive: behaves as if the permissive property
436                                  was present
437         :returns: a `setting.owners.Owner` object
438         """
439         if isinstance(opt, SymLinkOption) and \
440                 not isinstance(opt, DynSymLinkOption):
441             opt = opt._impl_getopt()
442         path = opt.impl_getpath(self._getcontext())
443         return self._getowner(opt, path, index=index, force_permissive=force_permissive)
444
445     def _getowner(self, opt, path, validate_properties=True,
446                   force_permissive=False, validate_meta=undefined,
447                   self_properties=undefined, only_default=False,
448                   index=None):
449         """get owner of an option
450         """
451         if not isinstance(opt, Option) and not isinstance(opt,
452                                                           DynSymLinkOption):
453             raise ConfigError(_('owner only avalaible for an option'))
454         context = self._getcontext()
455         if self_properties is undefined:
456             self_properties = context.cfgimpl_get_settings()._getproperties(
457                 opt, path, read_write=False)
458         if 'frozen' in self_properties and 'force_default_on_freeze' in self_properties:
459             return owners.default
460         if validate_properties:
461             self._getitem(opt, path, True, force_permissive, None, True,
462                           self_properties=self_properties)
463         owner = self._p_.getowner(path, owners.default, only_default=only_default, index=index)
464         if validate_meta is undefined:
465             if opt.impl_is_master_slaves('slave'):
466                 master = opt.impl_get_master_slaves().getmaster(opt)
467                 masterp = master.impl_getpath(context)
468                 validate_meta = self._is_meta(opt, masterp)
469             else:
470                 validate_meta = True
471         if validate_meta:
472             meta = context.cfgimpl_get_meta()
473             if owner is owners.default and meta is not None:
474                 owner = meta.cfgimpl_get_values()._getowner(opt, path,
475                                                             validate_properties=validate_properties,
476                                                             force_permissive=force_permissive,
477                                                             self_properties=self_properties,
478                                                             only_default=only_default, index=index)
479         return owner
480
481     def setowner(self, opt, owner):
482         """
483         sets a owner to an option
484
485         :param opt: the `option.Option` object
486         :param owner: a valid owner, that is a `setting.owners.Owner` object
487         """
488         if not isinstance(owner, owners.Owner):  # pragma: optional cover
489             raise TypeError(_("invalid generic owner {0}").format(str(owner)))
490
491         path = opt.impl_getpath(self._getcontext())
492         if not self._p_.hasvalue(path):  # pragma: optional cover
493             raise ConfigError(_('no value for {0} cannot change owner to {1}'
494                                 '').format(path, owner))
495         self._getcontext().cfgimpl_get_settings().validate_properties(opt,
496                                                                       False,
497                                                                       True,
498                                                                       path)
499
500         self._p_.setowner(path, owner)
501
502     def is_default_owner(self, opt, validate_properties=True,
503                          validate_meta=True, index=None):
504         """
505         :param config: *must* be only the **parent** config
506                        (not the toplevel config)
507         :return: boolean
508         """
509         path = opt.impl_getpath(self._getcontext())
510         return self._is_default_owner(opt, path,
511                                       validate_properties=validate_properties,
512                                       validate_meta=validate_meta, index=index)
513
514     def _is_default_owner(self, opt, path, validate_properties=True,
515                           validate_meta=True, self_properties=undefined,
516                           index=None):
517         if not opt.impl_is_master_slaves('slave'):
518             index = None
519         d = self._getowner(opt, path, validate_properties,
520                            validate_meta=validate_meta,
521                            self_properties=self_properties, only_default=True,
522                            index=index)
523         return d == owners.default
524
525     def reset_cache(self, only_expired):
526         """
527         clears the cache if necessary
528         """
529         if only_expired:
530             self._p_.reset_expired_cache(int(time()))
531         else:
532             self._p_.reset_all_cache()
533
534     # information
535     def set_information(self, key, value):
536         """updates the information's attribute
537
538         :param key: information's key (ex: "help", "doc"
539         :param value: information's value (ex: "the help string")
540         """
541         self._p_.set_information(key, value)
542
543     def get_information(self, key, default=undefined):
544         """retrieves one information's item
545
546         :param key: the item string (ex: "help")
547         """
548         try:
549             return self._p_.get_information(key)
550         except ValueError:  # pragma: optional cover
551             if default is not undefined:
552                 return default
553             else:
554                 raise ValueError(_("information's item"
555                                    " not found: {0}").format(key))
556
557     def mandatory_warnings(self, force_permissive=False, validate=True):
558         """convenience function to trace Options that are mandatory and
559         where no value has been set
560
561         :param force_permissive: do raise with permissives properties
562         :type force_permissive: `bool`
563         :param validate: validate value when calculating properties
564         :type validate: `bool`
565
566         :returns: generator of mandatory Option's path
567         """
568         context = self._getcontext()
569         settings = context.cfgimpl_get_settings()
570         setting_properties = context.cfgimpl_get_settings()._getproperties(
571             read_write=False)
572
573         def _mandatory_warnings(description, currpath=None):
574             if currpath is None:
575                 currpath = []
576             for opt in description._impl_getchildren(context=context):
577                 name = opt.impl_getname()
578                 path = '.'.join(currpath + [name])
579
580                 if opt.impl_is_optiondescription():
581                     try:
582                         settings.validate_properties(opt, True, False, path=path,
583                                                      force_permissive=force_permissive,
584                                                      setting_properties=setting_properties)
585                     except PropertiesOptionError as err:
586                         pass
587                     else:
588                         for path in _mandatory_warnings(opt, currpath + [name]):
589                             yield path
590                 else:
591                     if isinstance(opt, SymLinkOption) and \
592                             not isinstance(opt, DynSymLinkOption):
593                         true_opt = opt._impl_getopt()
594                         true_path = descr.impl_get_path_by_opt(true_opt)
595                     else:
596                         true_opt = opt
597                         true_path = path
598                     #FIXME attention c'est réutilisé donc jamais complet ??
599                     self_properties = settings._getproperties(true_opt, true_path,
600                                                               read_write=False,
601                                                               setting_properties=setting_properties)
602                     if 'mandatory' in self_properties:
603                         try:
604                             self._get_cached_item(true_opt, path=true_path,
605                                                   force_properties=frozenset(('mandatory',)),
606                                                   force_permissive=force_permissive,
607                                                   setting_properties=setting_properties,
608                                                   self_properties=self_properties,
609                                                   validate=validate)
610                         except PropertiesOptionError as err:
611                             if err.proptype == ['mandatory']:
612                                 yield path
613                         except ConfigError as err:
614                             if validate:
615                                 raise err
616                             else:
617                                 #assume that uncalculated value is an empty value
618                                 yield path
619
620         descr = self._getcontext().cfgimpl_get_description()
621         for path in _mandatory_warnings(descr):
622             yield path
623
624     def force_cache(self):
625         """parse all option to force data in cache
626         """
627         context = self.context()
628         if not 'cache' in context.cfgimpl_get_settings():
629             raise ConfigError(_('can force cache only if cache '
630                                 'is actived in config'))
631         #remove all cached properties and value to update "expired" time
632         context.cfgimpl_reset_cache()
633         for path in context.cfgimpl_get_description().impl_getpaths(
634                 include_groups=True):
635             try:
636                 context.getattr(path)
637             except PropertiesOptionError:
638                 pass
639
640     def __getstate__(self):
641         return {'_p_': self._p_}
642
643     def _impl_setstate(self, storage):
644         self._p_._storage = storage
645
646     def __setstate__(self, states):
647         self._p_ = states['_p_']
648
649
650 # ____________________________________________________________
651 # multi types
652 class Multi(list):
653     """multi options values container
654     that support item notation for the values of multi options"""
655     __slots__ = ('opt', 'path', 'context', '__weakref__')
656
657     def __init__(self, value, context, opt, path):
658         """
659         :param value: the Multi wraps a list value
660         :param context: the home config that has the values
661         :param opt: the option object that have this Multi value
662         :param path: path of the option
663         """
664         if value is None:
665             value = []
666         if not opt.impl_is_submulti() and isinstance(value, Multi):  # pragma: optional cover
667             raise ValueError(_('{0} is already a Multi ').format(
668                 opt.impl_getname()))
669         self.opt = opt
670         self.path = path
671         if not isinstance(context, weakref.ReferenceType):  # pragma: optional cover
672             raise ValueError('context must be a Weakref')
673         self.context = context
674         if not isinstance(value, list):
675             if not '_index' in self.__slots__ and opt.impl_is_submulti():
676                 value = [[value]]
677             else:
678                 value = [value]
679         elif value != [] and not '_index' in self.__slots__ and \
680                 opt.impl_is_submulti() and not isinstance(value[0], list):
681             value = [value]
682         super(Multi, self).__init__(value)
683         if opt.impl_is_submulti():
684             if not '_index' in self.__slots__:
685                 for idx, val in enumerate(self):
686                     if not isinstance(val, SubMulti):
687                         super(Multi, self).__setitem__(idx, SubMulti(val,
688                                                                      context,
689                                                                      opt, path,
690                                                                      idx))
691                     self[idx].submulti = weakref.ref(self)
692
693     def _getcontext(self):
694         """context could be None, we need to test it
695         context is None only if all reference to `Config` object is deleted
696         (for example we delete a `Config` and we manipulate a reference to
697         old `SubConfig`, `Values`, `Multi` or `Settings`)
698         """
699         context = self.context()
700         if context is None:  # pragma: optional cover
701             raise ConfigError(_('the context does not exist anymore'))
702         return context
703
704     def __setitem__(self, index, value):
705         self._setitem(index, value)
706
707     def _setitem(self, index, value, validate=True):
708         context = self._getcontext()
709         setting = context.cfgimpl_get_settings()
710         setting_properties = setting._getproperties(read_write=False)
711         if 'validator' in setting_properties and validate:
712             fake_context = context._gen_fake_values()
713             fake_multi = fake_context.cfgimpl_get_values()._get_cached_item(
714                 self.opt, path=self.path, validate=False)
715             fake_multi._setitem(index, value, validate=False)
716             self._validate(value, fake_context, index, True)
717         #assume not checking mandatory property
718         super(Multi, self).__setitem__(index, value)
719         self._store()
720
721     #def __repr__(self, *args, **kwargs):
722     #    return super(Multi, self).__repr__(*args, **kwargs)
723
724     #def __getitem__(self, y):
725     #    return super(Multi, self).__getitem__(y)
726
727     def _get_validated_value(self, index):
728         values = self._getcontext().cfgimpl_get_values()
729         return values._get_validated_value(self.opt, self.path,
730                                            True, False, None, True,
731                                            index=index)
732
733     def append(self, value=undefined, force=False, setitem=True, validate=True):
734         """the list value can be updated (appened)
735         only if the option is a master
736         """
737         if not force and self.opt.impl_is_master_slaves('slave'):  # pragma: optional cover
738             raise SlaveError(_("cannot append a value on a multi option {0}"
739                                " which is a slave").format(self.opt.impl_getname()))
740         index = self.__len__()
741         if value is undefined:
742             value = self._get_validated_value(index)
743         context = self._getcontext()
744         setting = context.cfgimpl_get_settings()
745         setting_properties = setting._getproperties(read_write=False)
746         if 'validator' in setting_properties and validate and value not in [None, undefined]:
747             fake_context = context._gen_fake_values()
748             fake_multi = fake_context.cfgimpl_get_values()._get_cached_item(
749                 self.opt, path=self.path, validate=False)
750             fake_multi.append(value, validate=False, force=True)
751             self._validate(value, fake_context, index, True)
752         if not '_index' in self.__slots__ and self.opt.impl_is_submulti():
753             if not isinstance(value, SubMulti):
754                 value = SubMulti(value, self.context, self.opt, self.path, index)
755             value.submulti = weakref.ref(self)
756         super(Multi, self).append(value)
757         if setitem:
758             self._store(force=force)
759
760     def sort(self, cmp=None, key=None, reverse=False):
761         if self.opt.impl_is_master_slaves():
762             raise SlaveError(_("cannot sort multi option {0} if master or slave"
763                                "").format(self.opt.impl_getname()))
764         if sys.version_info[0] >= 3:
765             if cmp is not None:
766                 raise ValueError(_('cmp is not permitted in python v3 or '
767                                    'greater'))
768             super(Multi, self).sort(key=key, reverse=reverse)
769         else:
770             super(Multi, self).sort(cmp=cmp, key=key, reverse=reverse)
771         self._store()
772
773     def reverse(self):
774         if self.opt.impl_is_master_slaves():
775             raise SlaveError(_("cannot reverse multi option {0} if master or "
776                                "slave").format(self.opt.impl_getname()))
777         super(Multi, self).reverse()
778         self._store()
779
780     def insert(self, index, value, validate=True):
781         if self.opt.impl_is_master_slaves():
782             raise SlaveError(_("cannot insert multi option {0} if master or "
783                                "slave").format(self.opt.impl_getname()))
784         context = self._getcontext()
785         setting = setting = context.cfgimpl_get_settings()
786         setting_properties = setting._getproperties(read_write=False)
787         if 'validator' in setting_properties and validate and value is not None:
788             fake_context = context._gen_fake_values()
789             fake_multi = fake_context.cfgimpl_get_values()._get_cached_item(
790                 self.opt, path=self.path, validate=False)
791             fake_multi.insert(index, value, validate=False)
792             self._validate(value, fake_context, index, True)
793         super(Multi, self).insert(index, value)
794         self._store()
795
796     def extend(self, iterable, validate=True):
797         if self.opt.impl_is_master_slaves():
798             raise SlaveError(_("cannot extend multi option {0} if master or "
799                                "slave").format(self.opt.impl_getname()))
800         try:
801             index = self._index
802         except:
803             index = None
804         context = self._getcontext()
805         setting = context.cfgimpl_get_settings()
806         setting_properties = setting._getproperties(read_write=False)
807         if 'validator' in setting_properties and validate:
808             fake_context = context._gen_fake_values()
809             fake_multi = fake_context.cfgimpl_get_values()._get_cached_item(
810                 self.opt, path=self.path, validate=False)
811             fake_multi.extend(iterable, validate=False)
812             self._validate(iterable, fake_context, index)
813         super(Multi, self).extend(iterable)
814         self._store()
815
816     def _validate(self, value, fake_context, force_index, submulti=False):
817         self.opt.impl_validate(value, context=fake_context,
818                                force_index=force_index)
819
820     def pop(self, index, force=False):
821         """the list value can be updated (poped)
822         only if the option is a master
823
824         :param index: remove item a index
825         :type index: int
826         :param force: force pop item (withoud check master/slave)
827         :type force: boolean
828         :returns: item at index
829         """
830         context = self._getcontext()
831         if not force:
832             if self.opt.impl_is_master_slaves('slave'):  # pragma: optional cover
833                 raise SlaveError(_("cannot pop a value on a multi option {0}"
834                                    " which is a slave").format(self.opt.impl_getname()))
835             if self.opt.impl_is_master_slaves('master'):
836                 self.opt.impl_get_master_slaves().pop(self.opt,
837                                                       context.cfgimpl_get_values(), index)
838         #set value without valid properties
839         ret = super(Multi, self).pop(index)
840         self._store(force=force)
841         return ret
842
843     def _store(self, force=False):
844         self._getcontext().cfgimpl_get_values()._setvalue(self.opt, self.path,
845                                                           self,
846                                                           validate_properties=not force)
847
848
849 class SubMulti(Multi):
850     __slots__ = ('_index', 'submulti')
851
852     def __init__(self, value, context, opt, path, index):
853         """
854         :param index: index (only for slave with submulti)
855         :type index: `int`
856         """
857         self._index = index
858         super(SubMulti, self).__init__(value, context, opt, path)
859
860     def append(self, value=undefined):
861         super(SubMulti, self).append(value, force=True)
862
863     def pop(self, index):
864         return super(SubMulti, self).pop(index, force=True)
865
866     def __setitem__(self, index, value):
867         self._setitem(index, value)
868
869     def _store(self, force=False):
870         #force is unused here
871         self._getcontext().cfgimpl_get_values()._setvalue(self.opt,
872                                                           self.path,
873                                                           self.submulti())
874
875     def _validate(self, value, fake_context, force_index, submulti=False):
876         if value is not None:
877             if submulti is False:
878                 super(SubMulti, self)._validate(value, fake_context,
879                                                 force_index, submulti)
880             else:
881                 self.opt.impl_validate(value, context=fake_context,
882                                        force_index=self._index,
883                                        force_submulti_index=force_index)
884
885     def _get_validated_value(self, index):
886         values = self._getcontext().cfgimpl_get_values()
887         return values._get_validated_value(self.opt, self.path,
888                                            True, False, None, True,
889                                            index=index,
890                                            submulti_index=self._index)