Example #1
0
File: conf.py Project: lcrees/stage
 def __init__(self, conf=None):
     super(env, self).__init__()
     self._join = join = '.'.join
     self._conf = envz = environ
     if conf is not None:
         dumps = pickle.dumps
         b64enc = b64encode
         # populate os.environ
         for k, v in items(conf):
             for x, y in items(v):
                 envz[join((k, x))] = b64enc(dumps(y)).decode('utf-8')
Example #2
0
    def templates(self, tempdict):
        '''
        Sets inline text and attribute templates for child fields.

        :argument dict tempdict: Dictionary of templates
        '''
        if isinstance(tempdict, dict):
            # make sure there are no more templates than there are fields
            if len(tempdict) <= len(self):
                self._templates = tempdict
                fielddict = self._fielddict
                XGroup = _XMLGroup
                for key, value in items(tempdict):
                    item = fielddict[key]
                    # handle groups
                    if isinstance(item, XGroup):
                        item.templates(value)
                    # handle fields
                    elif not hasattr(item, 'groupmark'):
                        # check if text template is in dict
                        try:
                            item.template = value['text']
                        except KeyError:
                            pass
                        # check if attribute template is in dict
                        try:
                            item.atemplates(value['attrib'])
                        except KeyError:
                            pass
            # raise exception if more templates than fields
            else:
                raise TypeError('template count exceeds field count')
        else:
            raise TypeError('invalid source for templates')
Example #3
0
File: utils.py Project: lcrees/stuf
def exhaustmap(mapping, call, filter=False, exception=StopIteration, _n=next):
    '''
    call `next` on an iterator until it's exhausted

    @param mapping: a mapping to exhaust
    @param call: call to handle what survives the filter
    @param filter: a filter to apply to mapping (default: `None`)
    @param exception: exception sentinel (default: `StopIteration`)
    '''
    subiter = ifilter(filter, items(mapping)) if filter else items(mapping)
    iterable = starmap(call, subiter)
    try:
        while True:
            _n(iterable)
    except exception:
        pass
Example #4
0
 def _setelement(self, tree):
     # set internal element.
     self.__name__ = _checkname(tree.attrib[self.mark])
     # set internal element and backup tree
     self._tree, self._btree = tree, _copytree(tree)
     # make tree attribute dictionary a field attribute
     self._attrib, tattrib = tree.attrib, dict()
     # if inline text template in tree, assign it to template
     try:
         self.template = tree.text
     except TypeError:
         pass
     checkname_ = _checkname
     auto = self._auto
     mark = self.mark
     setattr_ = setattr
     cls = self.__class__
     for attr, atext in items(self._attrib):
         # if attribute template text in template source, add to _tattrib
         if '$' in atext or '%' in atext:
             tattrib[attr] = atext
         # make XML attrs attributes of self if automagic on & not a mark
         if auto and attr != mark:
             name = checkname_(attr)
             # set new class as attribute of self's superclass
             setattr_(cls, name, _Attribute(attr, name))
     # assign any attribute templates
     if tattrib:
         self.atemplates(tattrib)
Example #5
0
 def test_items(self):
     self.store['max'] = 3
     self.store['min'] = 6
     self.store['pow'] = 7
     self.store.sync()
     slist = list(items(self.store))
     self.assertEqual(('min', 6) in slist, True)
Example #6
0
File: utils.py Project: lcrees/stuf
def exhaustmap(mapping, call, filter=False, exception=StopIteration, _n=next):
    '''
    call `next` on an iterator until it's exhausted

    @param mapping: a mapping to exhaust
    @param call: call to handle what survives the filter
    @param filter: a filter to apply to mapping (default: `None`)
    @param exception: exception sentinel (default: `StopIteration`)
    '''
    subiter = ifilter(filter, items(mapping)) if filter else items(mapping)
    iterable = starmap(call, subiter)
    try:
        while True:
            _n(iterable)
    except exception:
        pass
Example #7
0
 def test_items(self):
     self.store['max'] = 3
     self.store['min'] = 6
     self.store['pow'] = 7
     self.store.sync()
     slist = list(items(self.store))
     self.assertEqual(('min', 6) in slist, True)
Example #8
0
 def items(self):
     loads = self.loads
     try:
         self._store.execute("SELECT data as i FROM shove")
         for k, v in items(self._store.fetchall()["i"]):
             yield k, loads(v, k)
     except psycopg2.ProgrammingError:
         self._conn.rollback()
Example #9
0
File: base.py Project: lcrees/stuf
 def __iter__(self):
     cls = self.__class__
     for key, value in items(self):
         # nested stuf of some sort
         if isinstance(value, cls):
             yield key, dict(iter(value))
         # normal key, value pair
         else:
             yield key, value
Example #10
0
def _copyetree(tree, builder):
    # copies an element to a different ElementTree implementation.
    element = builder(tree.tag, dict(items(tree.attrib)))
    element.tail, element.text = tree.tail, tree.text
    eappend = element.append
    copyetree = _copyetree
    for child in tree:
        eappend(copyetree(child, builder))
    return element
Example #11
0
File: base.py Project: lcrees/stuf
 def __iter__(self):
     cls = self.__class__
     for key, value in items(self):
         # nested stuf of some sort
         if isinstance(value, cls):
             yield key, dict(iter(value))
         # normal key, value pair
         else:
             yield key, value
Example #12
0
File: base.py Project: lcrees/stuf
 def __getattr__(self, key, _getter=object.__getattribute__):
     try:
         return self[key]
     except KeyError:
         if key == 'iteritems':
             return items(self)
         elif key == 'iterkeys':
             return keys(self)
         elif key == 'itervalues':
             return values(self)
         return _getter(self, key)
Example #13
0
        def most_common(self, n=None):
            '''
            list the n most common elements and their counts from the most
            common to the least

            If n is None, then list all element counts.
            '''
            # Emulate Bag.sortedByCount from Smalltalk
            if n is None:
                return sorted(items(self), key=itemgetter(1), reverse=True)
            return heapq.nlargest(n, self.iteritems(), key=itemgetter(1))
Example #14
0
File: core.py Project: lcrees/stuf
 def __getattr__(self, key, _getter=object.__getattribute__):
     try:
         if key == 'iteritems':
             return items(self)
         elif key == 'iterkeys':
             return keys(self)
         elif key == 'itervalues':
             return values(self)
         return _getter(self, key)
     except AttributeError:
         return self[key]
Example #15
0
File: utils.py Project: lcrees/stuf
def inverse_lookup(value, this, default=None):
    '''
    get attribute of an instance by value

    @param value: value to lookup as a key
    @param this: instance to check for attribute
    @param default: default key (default: None)
    '''
    try:
        return itemgetter(value)(dict((v, k) for k, v in items(vars(this))))
    except (TypeError, KeyError):
        return default
Example #16
0
    def update(self, attr):
        '''
        Set internal element attributes with :class:`dict`.

        :argument dict attr: element attributes
        '''
        if isinstance(attr, dict):
            _setattr = self._setattr
            for key, value in items(attr):
                _setattr(key, value)
        else:
            raise TypeError('invalid attribute source')
Example #17
0
 def __imod__(self, data):
     """
     Substitutes text data into each field's template and the modified
     template (self) is returned.
     """
     # get any templates
     try:
         self.templates(data.pop("templates"))
     except (AttributeError, KeyError):
         pass
     # get any substitutions
     try:
         self.__ipow__(data.pop("subs"))
     except (AttributeError, KeyError):
         pass
     # cache field and data length
     lself, length = len(self._fields), len(data)
     # if number of fields == number of items in data...
     if length == lself:
         fielddict = self._fielddict
         if isinstance(data, dict):
             for key, value in items(data):
                 # if tuple, expand it
                 try:
                     fielddict[key].__ipow__(value)
                 # if dictionary, substitute it
                 except TypeError:
                     fielddict[key].__imod__(value)
         elif isinstance(data, tuple):
             fields = self._fields
             # iterate with index and item through data
             for key, item in enumerate(data):
                 # if item is a tuple, expand it
                 try:
                     fields[key].__ipow__(item)
                 # if dictionary, substitute it
                 except TypeError:
                     fields[key].__imod__(item)
         else:
             raise TypeError(_exceptions[2])
     # return self if no more items in data
     elif length == 0:
         return self
     # raise exception if too many items to match all fields
     elif length > lself:
         raise TypeError(_exceptions[3])
     # raise exception if too few items to match all fields
     elif length < lself:
         raise TypeError(_exceptions[4])
     return self
Example #18
0
 def __delitem__(self, key):
     # handle positional indexes
     try:
         # get field
         obj = self._fields[key]
         # get field name
         for name, element in items(self._fielddict):
             if element == obj:
                 break
     # handle keys
     except TypeError:
         name = key
     # delete object attribute
     self.__delattr__(name)
Example #19
0
File: utils.py Project: lcrees/stuf
 def wrapper(*args, **kw):
     key = args
     if kw:
         key += tuple(sorted(items(kw)))
     try:
         result = cache.pop(key)
     except KeyError:
         result = this(*args, **kw)
         # purge least recently used cache entry
         if len(cache) >= maxsize:
             cache.popitem(0)
     # record recent use of this key
     cache[key] = result
     return result
Example #20
0
def object_walk(this):
    '''
    transform classes within an instance into a dictionary

    @param this: object
    '''
    this_stuf = dict()
    for k, v in items(vars(this)):
        if not k.startswith('_'):
            if isclass(v):
                this_stuf[k] = object_walk(v)
            else:
                this_stuf[k] = v
    return this_stuf
Example #21
0
File: utils.py Project: lcrees/stuf
def inverse_lookup(value, this, default=None):
    '''
    get attribute of an instance by value

    @param value: value to lookup as a key
    @param this: instance to check for attribute
    @param default: default key (default: None)
    '''
    try:
        return itemgetter(value)(
            dict((v, k) for k, v in items(vars(this)))
        )
    except (TypeError, KeyError):
        return default
Example #22
0
File: utils.py Project: lcrees/stuf
 def wrapper(*args, **kw):
     key = args
     if kw:
         key += tuple(sorted(items(kw)))
     try:
         result = cache.pop(key)
     except KeyError:
         result = this(*args, **kw)
         # purge least recently used cache entry
         if len(cache) >= maxsize:
             cache.popitem(0)
     # record recent use of this key
     cache[key] = result
     return result
Example #23
0
 def __init__(self, context, stype, newkey, **options):
     self.context = context
     self._type = stype
     self._type_name = newkey
     self._socket = xs.socket(context._ctx, stype)
     options.update(context._options)
     _set = self._set
     rc = 0
     for k, v in items(options):
         rc |= _set(k, v)
     self.last_rc = rc
     context.sockets[self.id] = self
     self.closed = False
     self.connections = OrderedDict()
     self.bindings = OrderedDict()
Example #24
0
File: base.py Project: lcrees/stuf
 def _build(cls, iterable, _map=imap, _is=isinstance, _list=exhaust):
     kind = cls._map
     # add class to handle potential nested objects of the same class
     kw = kind()
     update = kw.update
     if _is(iterable, Mapping):
         update(kind(items(iterable)))
     elif _is(iterable, Sequence):
         # extract appropriate key-values from sequence
         def _coro(arg, update=update):
             try:
                 update(arg)
             except (ValueError, TypeError):
                 pass
         _list(_map(_coro, iterable))
     return kw
Example #25
0
File: base.py Project: lcrees/stuf
    def _build(cls, iterable, _map=imap, _is=isinstance, _list=exhaust):
        kind = cls._map
        # add class to handle potential nested objects of the same class
        kw = kind()
        update = kw.update
        if _is(iterable, Mapping):
            update(kind(items(iterable)))
        elif _is(iterable, Sequence):
            # extract appropriate key-values from sequence
            def _coro(arg, update=update):
                try:
                    update(arg)
                except (ValueError, TypeError):
                    pass

            _list(_map(_coro, iterable))
        return kw
Example #26
0
    def atemplates(self, attr):
        '''
        Sets templates for the internal element's attributes.

        :argument attr: attribute template
        '''
        if isinstance(attr, dict):
            tattrib = dict()
            # set template for each item in attrib dict
            Stemplate = _Stemplate
            for key, value in items(attr):
                # make string.template instance if delimiter '$' is found
                if '$' in value:
                    tattrib[key] = Stemplate(value)
                # use standard Python format string if delimiter '%' found
                elif '%' in value:
                    tattrib[key] = value
                # raise exception if no delimiter found
                else:
                    raise TypeError(_exceptions[8])
            # assign object attribute for attribute template dictionary
            self._tattrib.update(tattrib)
        else:
            raise TypeError(_exceptions[7])
Example #27
0
File: utils.py Project: lcrees/stuf
        return self.expr(that) if this is None else self._set(this)


class either(bothbase):

    '''
    descriptor that caches results of both instance- and class-level results
    '''

    def __get__(self, this, that):
        if this is None:
            return setter(that, self.name, self.expr(that))
        return self._set(this)


class twoway(bothbase):

    '''descriptor that enables instance and class-level results'''

    def __get__(self, this, that):
        return self.expr(that) if this is None else self.method(this)


lru_wrapped = lru
get_or_default = getdefault

__all__ = sorted(name for name, obj in items(locals()) if not any([
    name.startswith('_'), ismodule(obj),
]))
del ismodule
Example #28
0
 def reset(self):
     '''reset previously accessed `lazybase` attributes'''
     this = vars(self)
     t = lambda x, y: x in this and isinstance(y, lazybase)
     exhaustmap(items(vars(getcls(self))), delattr, t)
Example #29
0
File: conf.py Project: lcrees/stage
 def __iter__(self):
     for k, v in items(self._all):
         yield k, v
Example #30
0
File: utils.py Project: lcrees/stuf
    class-level results
    '''
    def __get__(self, this, that):
        return self.expr(that) if this is None else self._set(this)


class either(bothbase):
    '''
    descriptor that caches results of both instance- and class-level results
    '''
    def __get__(self, this, that):
        if this is None:
            return setter(that, self.name, self.expr(that))
        return self._set(this)


class twoway(bothbase):
    '''descriptor that enables instance and class-level results'''
    def __get__(self, this, that):
        return self.expr(that) if this is None else self.method(this)


lru_wrapped = lru
get_or_default = getdefault

__all__ = sorted(name for name, obj in items(locals()) if not any([
    name.startswith('_'),
    ismodule(obj),
]))
del ismodule