settings.py 22.8 KB
Newer Older
1 2 3 4 5 6 7
# -*- coding: utf-8 -*-
#
# This file is part of the bliss project
#
# Copyright (c) 2016 Beamline Control Unit, ESRF
# Distributed under the GNU LGPLv3. See LICENSE for more info.

8
from .conductor import client
9
from bliss.common.utils import Null
10
from bliss import setup_globals
Matias Guijarro's avatar
Matias Guijarro committed
11 12 13
import weakref
import pickle

14

Matias Guijarro's avatar
Matias Guijarro committed
15
def get_cache():
16
    return client.get_cache(db=0)
Matias Guijarro's avatar
Matias Guijarro committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

def boolify(s,**keys):
    if s == 'True' or s == 'true':
            return True
    if s == 'False' or s == 'false':
            return False
    raise ValueError('Not Boolean Value!')

def auto_conversion(var):
    '''guesses the str representation of the variables type'''
    if var is None:
        return None
    for caster in (boolify,int, float):
        try:
            return caster(var)
        except ValueError:
            pass
    return var

36
def pickle_loads(var):
Matias Guijarro's avatar
Matias Guijarro committed
37 38 39 40 41 42 43 44 45 46 47 48
    if var is None:
        return None
    return pickle.loads(var)

def ttl_func(cnx,name,value = -1):
    if value is None:
        return cnx.persist(name)
    elif value is -1:
        return cnx.ttl(name)
    else:
        return cnx.expire(name,value)

49 50
def read_decorator(func):
    def _read(self,*args,**keys):
Matias Guijarro's avatar
Matias Guijarro committed
51 52
        value = func(self,*args,**keys)
        if self._read_type_conversion:
53
            if isinstance(value,list):
Matias Guijarro's avatar
Matias Guijarro committed
54
                value = [self._read_type_conversion(x) for x in value]
55
            elif isinstance(value,dict):
Matias Guijarro's avatar
Matias Guijarro committed
56 57
                for k,v in value.iteritems():
                    value[k] = self._read_type_conversion(v)
58 59 60 61
                if hasattr(self,'default_values') and isinstance(self.default_values,dict):
                    tmp = dict(self._default_values)
                    tmp.update(value)
                    value = tmp
Matias Guijarro's avatar
Matias Guijarro committed
62 63
            else:
                value = self._read_type_conversion(value)
64 65 66 67 68 69
        if value is None:
            if hasattr(self,'_default_value'):
                value = self._default_value
            elif(hasattr(self,'_default_values') and 
                 hasattr(self._default_values,'get')):
                value = self._default_values.get(args[0])
Matias Guijarro's avatar
Matias Guijarro committed
70 71 72
        return value
    return _read

73 74
def write_decorator_dict(func):
    def _write(self,values,**keys):
Matias Guijarro's avatar
Matias Guijarro committed
75 76 77 78 79 80 81 82 83 84
        if self._write_type_conversion:
            if not isinstance(values,dict) and values is not None:
                raise TypeError('can only be dict')

            if values is not None:
                for k,v in values.iteritems():
                    values[k] = self._write_type_conversion(v)
        return func(self,values,**keys)
    return _write

85
def write_decorator_multiple(func):
Matias Guijarro's avatar
Matias Guijarro committed
86 87 88 89 90 91 92 93 94
    def _write(self,values,**keys):
        if self._write_type_conversion:
            if not isinstance(values,(list,tuple)) and values is not None:
                raise TypeError('can only be tuple or list')
            if values is not None:
                values = [self._write_type_conversion(x) for x in values]
        return func(self,values,**keys)
    return _write

95
def write_decorator(func):
Matias Guijarro's avatar
Matias Guijarro committed
96 97 98 99 100 101
    def _write(self,value,**keys):
        if self._write_type_conversion and value is not None:
            value = self._write_type_conversion(value)
        return func(self,value,**keys)
    return _write

102 103 104 105 106 107 108 109 110 111 112 113
def scan(match='*',count=1000,connection=None):
    if connection is None:
        connection = get_cache()
    cursor = 0
    while 1:
        cursor,values = connection.scan(cursor=cursor,
                                        match=match,count=count)
        for val in values:
            yield val
        if int(cursor) == 0:
            break
        
114
class SimpleSetting(object):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
115 116
    def __init__(self,name,connection = None,
                 read_type_conversion = auto_conversion,
117
                 write_type_conversion = None,
118
                 default_value = None):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
119 120 121 122 123 124
        if connection is None:
            connection = get_cache()
        self._cnx = weakref.ref(connection)
        self._name = name
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
125
        self._default_value = default_value
Matias Guijarro's avatar
Matias Guijarro committed
126

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
127
    @read_decorator
128
    def get(self):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
129 130 131 132 133
        cnx = self._cnx()
        value = cnx.get(self._name)
        return value

    @write_decorator
134
    def set(self,value):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
135 136 137 138 139 140
        cnx = self._cnx()
        cnx.set(self._name,value)

    def ttl(self,value = -1):
        return ttl_func(self._cnx(),self._name,value)

141
    def __add__(self,other):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
142
        value = self.get()
143
        if isinstance(other,SimpleSetting):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
144 145 146 147 148 149
            other = other.get()
        return value + other

    def __iadd__(self,other):
        cnx = self._cnx()
        if cnx is not None:
150
            if isinstance(other,int):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
151 152
                if other == 1:
                    cnx.incr(self._name)
Matias Guijarro's avatar
Matias Guijarro committed
153
                else:
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
154
                    cnx.incrby(self._name,other)
155
            elif isinstance(other,float):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
156 157 158 159
                cnx.incrbyfloat(self._name,other)
            else:
                cnx.append(self._name,other)
            return self
Matias Guijarro's avatar
Matias Guijarro committed
160

161
    def __isub__(self,other):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
162 163 164
        if isinstance(other,basestring):
            raise TypeError("unsupported operand type(s) for -=: %s" % type(other).__name__)
        return self.__iadd__(-other)
Matias Guijarro's avatar
Matias Guijarro committed
165

166
    def __getitem__(self,ran):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
        cnx = self._cnx()
        if cnx is not None:
            step = None
            if isinstance(ran,slice):
                i,j = ran.start,ran.stop
                step = ran.step
            elif isinstance(ran,int):
                i = j = ran
            else:
                raise TypeError('indices must be integers')

            value = cnx.getrange(self._name,i,j)
            if step is not None:
                value = value[0:-1:step]
            return value


    def __repr__(self):
        cnx = self._cnx()
        value = cnx.get(self._name)
187
        return '<SimpleSetting name=%s value=%s>' % (self._name,value)
Matias Guijarro's avatar
Matias Guijarro committed
188

189
class SimpleSettingProp(object):
Matias Guijarro's avatar
Matias Guijarro committed
190 191 192
    def __init__(self,name,connection = None,
                 read_type_conversion = auto_conversion,
                 write_type_conversion = None,
193
                 default_value = None,
194
                 use_object_name = True):
Matias Guijarro's avatar
Matias Guijarro committed
195 196 197 198
        self._name = name
        self._cnx = connection or get_cache()
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
199
        self._default_value = default_value
Matias Guijarro's avatar
Matias Guijarro committed
200 201
        self._use_object_name = use_object_name

202
    def __get__(self,obj,type = None):
Matias Guijarro's avatar
Matias Guijarro committed
203 204 205 206
        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name
207 208 209 210
        return SimpleSetting(name,self._cnx,
                             self._read_type_conversion,
                             self._write_type_conversion,
                             self._default_value)
Matias Guijarro's avatar
Matias Guijarro committed
211

212
    def __set__(self,obj,value):
213
        if isinstance(value,SimpleSetting): return
Matias Guijarro's avatar
Matias Guijarro committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227

        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name

        if value is None:
            self._cnx.delete(name)
        else:
            if self._write_type_conversion:
                value = self._write_type_conversion(value)
            self._cnx.set(name,value)

class QueueSetting(object):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
228 229
    def __init__(self,name,connection = None,
                 read_type_conversion = auto_conversion,
230
                 write_type_conversion = None):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
231 232 233 234 235
        if connection is None: connection = get_cache()
        self._cnx = weakref.ref(connection)
        self._name = name
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
Matias Guijarro's avatar
Matias Guijarro committed
236

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
237
    @read_decorator
238
    def get(self,first=0,last=-1):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
239 240 241 242
        cnx = self._cnx()
        if first == last:
            l = cnx.lindex(self._name,first)
        else:
243 244
            if last != -1:
                last -= 1
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
245 246
            l = cnx.lrange(self._name,first,last)
        return l
Matias Guijarro's avatar
Matias Guijarro committed
247

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
248
    @write_decorator
249
    def append(self,value):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
250
        cnx = self._cnx()
251
        return cnx.rpush(self._name,value)
Matias Guijarro's avatar
Matias Guijarro committed
252

253 254 255 256
    def clear(self):
        cnx = self._cnx()
        cnx.delete(self._name)

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
257
    @write_decorator
258
    def prepend(self,value):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
259
        cnx = self._cnx()
260
        return cnx.lpush(self._name,value)
Matias Guijarro's avatar
Matias Guijarro committed
261

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
262
    @write_decorator_multiple
263
    def extend(self,values):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
264
        cnx = self._cnx()
265
        return cnx.rpush(self._name,*values)
Matias Guijarro's avatar
Matias Guijarro committed
266

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
267
    @write_decorator
268
    def remove(self,value):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
269
        cnx = self._cnx()
270
        cnx.lrem(self._name,value)
Matias Guijarro's avatar
Matias Guijarro committed
271

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
272
    @write_decorator_multiple
273
    def set(self,values):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
274 275
        if not isinstance(values,(list,tuple)) and values is not None:
            raise TypeError('can only be tuple or list')
Matias Guijarro's avatar
Matias Guijarro committed
276

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
277 278 279 280
        cnx = self._cnx()
        cnx.delete(self._name)
        if values is not None:
            cnx.rpush(self._name,*values)
Matias Guijarro's avatar
Matias Guijarro committed
281

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
282
    @write_decorator
283
    def set_item(self,value,pos = 0):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
284 285
        cnx = self._cnx()
        cnx.lset(self._name,pos,value)
Matias Guijarro's avatar
Matias Guijarro committed
286

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
287
    @read_decorator
288
    def pop_front(self):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
289 290 291 292 293 294 295
        cnx = self._cnx()
        value = cnx.lpop(self._name)
        if self._read_type_conversion:
            value = self._read_type_conversion(value)
        return value

    @read_decorator
296
    def pop_back(self):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
297 298 299 300 301 302 303 304 305
        cnx = self._cnx()
        value = cnx.rpop(self._name)
        if self._read_type_conversion:
            value = self._read_type_conversion(value)
        return value

    def ttl(self,value = -1):
        return ttl_func(self._cnx(),self._name,value)

306
    def __len__(self):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
307 308 309
        cnx = self._cnx()
        return cnx.llen(self._name)

310
    def __repr__(self):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
311 312
        cnx = self._cnx()
        value = cnx.lrange(self._name,0,-1)
313
        return '<QueueSetting name=%s value=%s>' % (self._name,value)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
314 315 316 317 318

    def __iadd__(self,other):
        self.extend(other)
        return self

319
    def __getitem__(self,ran):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
320
        if isinstance(ran,slice):
321 322
            i = ran.start is not None and ran.start or 0
            j = ran.stop is not None and ran.stop or -1
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
323 324 325 326
        elif isinstance(ran,int):
            i = j = ran
        else:
            raise TypeError('indices must be integers')
327 328 329 330 331
        value = self.get(first = i,last = j)
        if value is None:
            raise StopIteration
        else:
            return value
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
332

333
    def __iter__(self):
334 335
        cnx = self._cnx()
        lsize = cnx.llen(self._name)
336
        for first in xrange(0,lsize,1024):
337 338 339 340 341
            last = first + 1024
            if last >= lsize: last = -1
            for value in self.get(first,last):
                yield value
        
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
342
    def __setitem__(self,ran,value):
343 344
        if isinstance(ran,slice):
            for i,v in zip(range(ran.start,ran.stop),value):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
345 346 347 348 349 350 351 352
                self.set_item(v,pos=i)
        elif isinstance(ran,int):
            self.set_item(value,pos=ran)
        else:
            raise TypeError('indices must be integers')
        return self

class QueueSettingProp(object):
Matias Guijarro's avatar
Matias Guijarro committed
353 354 355
    def __init__(self,name,connection = None,
                 read_type_conversion = auto_conversion,
                 write_type_conversion = None,
356
                 use_object_name = True):
Matias Guijarro's avatar
Matias Guijarro committed
357 358 359 360 361 362
        self._name = name
        self._cnx = connection or get_cache()
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
        self._use_object_name = use_object_name

363
    def __get__(self,obj,type = None):
Matias Guijarro's avatar
Matias Guijarro committed
364 365 366 367 368
        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
369 370 371
        return QueueSetting(name,self._cnx,
                            self._read_type_conversion,
                            self._write_type_conversion)
Matias Guijarro's avatar
Matias Guijarro committed
372

373
    def __set__(self,obj,values):
374
        if isinstance(values,QueueSetting): return
Matias Guijarro's avatar
Matias Guijarro committed
375 376 377 378 379 380

        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name

Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
381 382 383
        proxy = QueueSetting(name,self._cnx,
                             self._read_type_conversion,
                             self._write_type_conversion)
Matias Guijarro's avatar
Matias Guijarro committed
384 385 386 387 388
        proxy.set(values)

class HashSetting(object):
    def __init__(self,name,connection=None,
                 read_type_conversion=auto_conversion,
389 390
                 write_type_conversion=None,
                 default_values = {}):
Matias Guijarro's avatar
Matias Guijarro committed
391 392 393 394 395 396
        if connection is None:
            connection = get_cache()
        self._cnx = weakref.ref(connection)
        self._name = name
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
397
        self._default_values = default_values
Matias Guijarro's avatar
Matias Guijarro committed
398

399 400
    def __repr__(self):
        value = self.get_all()
Matias Guijarro's avatar
Matias Guijarro committed
401
        return '<HashSetting name=%s value=%s>' % (self._name,value)
402
    
403
    def __delitem__(self,key):
404 405
        cnx = self._cnx()
        cnx.hdel(self._name,key)
Matias Guijarro's avatar
Matias Guijarro committed
406

407
    def __len__(self):
Matias Guijarro's avatar
Matias Guijarro committed
408 409 410 411 412 413 414
        cnx = self._cnx()
        return cnx.hlen(self._name)

    def ttl(self,value = -1):
        return ttl_func(self._cnx(),self._name,value)

    @read_decorator
415
    def get(self,key,default = None):
Matias Guijarro's avatar
Matias Guijarro committed
416
        cnx = self._cnx()
417 418 419 420
        return_val = cnx.hget(self._name,key)
        if return_val is None:
            return_val = default
        return return_val
Matias Guijarro's avatar
Matias Guijarro committed
421 422

    @read_decorator
423 424 425 426 427 428 429 430 431 432
    def pop(self,key,default = Null()):
        cnx = self._cnx().pipeline()
        cnx.hget(self._name,key)
        cnx.hdel(self._name,key)
        (value,worked) = cnx.execute()
        if not worked:
            if isinstance(default,Null):
                raise KeyError(key)
            else:
                value = default
Matias Guijarro's avatar
Matias Guijarro committed
433 434
        return value
    
435
    def remove(self,*key):
Matias Guijarro's avatar
Matias Guijarro committed
436
        cnx = self._cnx()
437
        cnx.hdel(self._name,*key)
Matias Guijarro's avatar
Matias Guijarro committed
438 439

    def get_all(self):
440 441 442 443 444 445
        all_dict = dict(self._default_values)
        all_dict.update(self._get_all())
        return all_dict

    @read_decorator
    def _get_all(self):
Matias Guijarro's avatar
Matias Guijarro committed
446 447 448
        cnx = self._cnx()
        return cnx.hgetall(self._name)
    
449
    def keys(self):
450
        return list(self.iterkeys())
Matias Guijarro's avatar
Matias Guijarro committed
451

452
    def values(self):
453
        return list(self.itervalues())
Matias Guijarro's avatar
Matias Guijarro committed
454

455
    def clear(self):
Matias Guijarro's avatar
Matias Guijarro committed
456 457 458
        cnx = self._cnx()
        cnx.delete(self._name)

459
    def copy(self):
Matias Guijarro's avatar
Matias Guijarro committed
460 461 462
        return self.get()

    @write_decorator_dict
463
    def set(self,values):
Matias Guijarro's avatar
Matias Guijarro committed
464 465 466 467 468 469
        cnx = self._cnx()
        cnx.delete(self._name)
        if values is not None:
            cnx.hmset(self._name,values)

    @write_decorator_dict
470
    def update(self,values):
Matias Guijarro's avatar
Matias Guijarro committed
471 472 473
        cnx = self._cnx()
        cnx.hmset(self._name,values)

474
    def items(self):
Matias Guijarro's avatar
Matias Guijarro committed
475 476 477 478
        values = self.get_all()
        return [(k,v) for k,v in values.iteritems()]

    @read_decorator
479
    def fromkeys(self,keys):
Matias Guijarro's avatar
Matias Guijarro committed
480 481 482
        cnx = self._cnx()
        return cnx.hmget(self._name,keys)
    
483
    def has_key(self,key):
Matias Guijarro's avatar
Matias Guijarro committed
484
        cnx = self._cnx()
485
        return cnx.hexists(self._name,key) or self._default_values.has_key(key)
Matias Guijarro's avatar
Matias Guijarro committed
486 487
    
    def iterkeys(self):
488 489 490
        for k,v in self.iteritems():
            yield k

Matias Guijarro's avatar
Matias Guijarro committed
491
    def itervalues(self):
492 493
        for k,v in self.iteritems():
            yield v
Matias Guijarro's avatar
Matias Guijarro committed
494

495
    def iteritems(self):
Matias Guijarro's avatar
Matias Guijarro committed
496 497
        cnx = self._cnx()
        next_id = 0
498
        seen_keys = set()
Matias Guijarro's avatar
Matias Guijarro committed
499 500 501 502 503
        while True:
            next_id,pd = cnx.hscan(self._name,next_id)
            for k,v in pd.iteritems():
                if self._read_type_conversion:
                    v = self._read_type_conversion(v)
504
                seen_keys.add(k)
Matias Guijarro's avatar
Matias Guijarro committed
505
                yield k,v
506
            if not next_id or next_id is '0':
Matias Guijarro's avatar
Matias Guijarro committed
507 508
                break

509 510 511 512
        for k,v in self._default_values.iteritems():
            if k in seen_keys: continue
            yield k,v

Matias Guijarro's avatar
Matias Guijarro committed
513 514 515
    def __getitem__(self,key):
        value = self.get(key)
        if value is None:
516 517
            if not self._default_values.has_key(key):
                raise KeyError(key)
Matias Guijarro's avatar
Matias Guijarro committed
518 519
        return value

520
    def __setitem__(self,key,value):
Matias Guijarro's avatar
Matias Guijarro committed
521
        cnx = self._cnx()
522 523 524
        if value is None:
            cnx.hdel(self._name,key)
            return
Matias Guijarro's avatar
Matias Guijarro committed
525 526 527 528 529 530 531 532
        if self._write_type_conversion:
            value = self._write_type_conversion(value)
        cnx.hset(self._name,key,value)

class HashSettingProp(object):        
    def __init__(self,name,connection = None,
                 read_type_conversion = auto_conversion,
                 write_type_conversion = None,
533
                 default_values = {},
534
                 use_object_name = True):
Matias Guijarro's avatar
Matias Guijarro committed
535 536 537 538
        self._name = name
        self._cnx = connection or get_cache()
        self._read_type_conversion = read_type_conversion
        self._write_type_conversion = write_type_conversion
539
        self._default_values = default_values
Matias Guijarro's avatar
Matias Guijarro committed
540 541 542 543 544 545 546 547 548 549
        self._use_object_name = use_object_name

    def __get__(self,obj,type = None):
        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name
    
        return HashSetting(name,self._cnx,
                           self._read_type_conversion,
550 551
                           self._write_type_conversion,
                           self._default_values)
Matias Guijarro's avatar
Matias Guijarro committed
552

553
    def __set__(self,obj,values):
Matias Guijarro's avatar
Matias Guijarro committed
554 555 556 557 558
        if self._use_object_name:
            name = obj.name + ':' + self._name
        else:
            name = self._name

559
        if isinstance(values,HashSetting): return
Matias Guijarro's avatar
Matias Guijarro committed
560

561 562 563 564
        proxy = HashSetting(name,self._cnx,
                            self._read_type_conversion,
                            self._write_type_conversion,
                            self._default_values)
Matias Guijarro's avatar
Matias Guijarro committed
565 566
        proxy.set(values)
    
567
    def get_proxy(self):
Matias Guijarro's avatar
Matias Guijarro committed
568 569
        return HashSetting(self._name,self._cnx,
                           self._read_type_conversion,
570 571
                           self._write_type_conversion,
                           self._default_values)
Matias Guijarro's avatar
Matias Guijarro committed
572 573
#helper

574
def _change_to_obj_marshalling(keys):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
575 576 577 578 579
    read_type_conversion = keys.pop('read_type_conversion',pickle_loads)
    write_type_conversion = keys.pop('write_type_conversion',pickle.dumps)
    keys.update({'read_type_conversion':read_type_conversion,
                 'write_type_conversion':write_type_conversion})

580 581 582
class HashObjSetting(HashSetting):
    def __init__(self,name,**keys):
        _change_to_obj_marshalling(keys)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
583 584
        HashSetting.__init__(self,name,**keys)

585
class HashObjSettingProp(HashSettingProp):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
586
    def __init__(self,name,**keys):
587
        _change_to_obj_marshalling(keys)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
588 589
        HashSettingProp.__init__(self,name,**keys)

590 591 592
class QueueObjSetting(QueueSetting):
    def __init__(self,name,**keys):
        _change_to_obj_marshalling(keys)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
593 594 595
        QueueSetting.__init__(self,name,**keys)

class QueueObjSettingProp(QueueSettingProp):
596 597
    def __init__(self,name,**keys):
        _change_to_obj_marshalling(keys)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
598 599
        QueueSettingProp.__init__(self,name,**keys)

600 601 602
class SimpleObjSetting(SimpleSetting):
    def __init__(self,name,**keys):
        _change_to_obj_marshalling(keys)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
603 604 605
        SimpleSetting.__init__(self,name,**keys)

class SimpleObjSettingProp(SimpleSettingProp):
606 607
    def __init__(self,name,**keys):
        _change_to_obj_marshalling(keys)
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
608
        SimpleSettingProp.__init__(self,name,**keys)
Matias Guijarro's avatar
Matias Guijarro committed
609

610 611 612
class Struct(object):
    def __init__(self,name,**keys):
        self._proxy = HashSetting(name,**keys)
613

614 615
    def __dir__(self):
        return self._proxy.keys()
616

617 618
    def __repr__(self):
        return "<Struct with attributes: %s>" % self._proxy.keys()
619

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    def __getattribute__(self, name):
        if name.startswith('_'):
            return object.__getattribute__(self,name)
        else:
            return self._proxy.get(name)
            
    def __setattr__(self,name,value):
        if name.startswith('_'):
            return object.__setattr__(self,name,value)
        else:
            self._proxy[name] = value
 
    def __delattr__(self,name):
        if name.startswith('_'):
            return object.__delattr__(self,name)
        else:
            self._proxy.remove(name)
637 638


639
class ParametersType(type):
640 641 642 643 644 645 646 647
    def __call__(cls, *args, **kwargs):
        class_dict = { '__slots__': tuple(cls.SLOTS), 'SLOTS':cls.SLOTS }
        new_cls = type(cls.__name__, (cls,), class_dict)
        return type.__call__(new_cls, *args, **kwargs)

    def __new__(cls, name, bases, attrs):
        attrs['__slots__'] = tuple(attrs['SLOTS'])
        return type.__new__(cls, name, bases, attrs)
Matias Guijarro's avatar
Matias Guijarro committed
648

649

650 651
class ParamDescriptor(object):
    OBJECT_PREFIX = 'object:'
652

653 654 655 656 657
    def __init__(self, proxy, name, value, assign = True):
        self.proxy = proxy 
        self.name = name
        if assign:
            self.assign(value)
658

659 660 661 662
    def assign(self, value):
        if hasattr(value, 'name') and hasattr(setup_globals, value.name):
            value = '%s%s' % (ParamDescriptor.OBJECT_PREFIX, value.name)
        self.proxy[self.name] = value
663 664 665 666 667 668

    def __get__(self, obj, obj_type):
        value = self.proxy[self.name]
        if isinstance(value, (str,unicode)) and value.startswith(ParamDescriptor.OBJECT_PREFIX):
            value = value[len(ParamDescriptor.OBJECT_PREFIX):]
            return getattr(setup_globals, value)
669
        return self.proxy[self.name]
670

671 672 673 674 675
    def __set__(self, obj, value):
        return self.assign(value)

    def __delete__(self, *args):
        del self.proxy[self.name]
676 677


678 679
class Parameters(object):
    __metaclass__ = ParametersType
680
    DESCRIPTOR = ParamDescriptor
681 682
    SLOTS = ['_proxy','__current_config']

683 684
    def __init__(self, name, **keys):
        self.__current_config = SimpleSetting(name, default_value='default')
685 686 687 688
        hash_name = '%s:%s' % (name, self.__current_config.get())
        self._proxy = HashSetting(hash_name, **keys)
        for key in self._proxy.iterkeys():
            self.add(key)
689 690

    def __dir__(self):
691 692
        return self._proxy.keys() + ['add','remove','switch','configs']
    
693 694 695 696 697 698 699 700
    def __repr__(self):
        rep_str = "Parameters : (%s)\n" % self.__current_config.get()
        d = dict(self._proxy.iteritems())
        max_len = max((len(x) for x in d.keys()))
        str_format = '  %-' + '%ds' % max_len + ' = %s\n'
        for key,value in d.iteritems():
            rep_str += str_format % (key,value)
        return rep_str
701 702 703 704 705 706 707 708
    
    def add(self, name, value = None):
        setattr(self.__class__, name, self.DESCRIPTOR(self._proxy, name, value,
                                                      value is not None))

    def remove(self, name):
        self._proxy.remove(name)
        delattr(self.__class__, name)
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726

    def switch(self,name):
        for key,value in dict(self.__class__.__dict__).iteritems():
            if isinstance(value, self.DESCRIPTOR):
                delattr(self.__class__,key)
                
        self.__current_config.set(name)

        basename = ":".join(self._proxy._name.split(':')[:-1])
        self._proxy._name = '%s:%s' % (basename, name)
        
        for key in self._proxy.keys():
            self.add(key)
        
    @property
    def configs(self):
        basename = ":".join(self._proxy._name.split(':')[:-1])
        return list((x.split(':')[-1] for x in scan(match='%s:*' % basename)))
Matias Guijarro's avatar
Matias Guijarro committed
727

728 729
if __name__ == "__main__":
    class A(object):
Sebastien Petitdemange's avatar
Sebastien Petitdemange committed
730 731 732 733 734 735
        x = SimpleSettingProp('counter')
        y = SimpleObjSettingProp('obj')
        q = QueueSettingProp('seb')
        ol = QueueObjSettingProp('seb-list')
        h = HashSettingProp('seb-hash')
        oh = HashObjSettingProp('seb-hash-object')
Matias Guijarro's avatar
Matias Guijarro committed
736 737 738 739 740
        def __init__(self,name):
            self.name = name

    a = A('m0')
    p = Struct('optics:zap:params')