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