Python Attribute Dictionary

"""
AttrDict: Attribute Dictionary with Default and Tree variations.
 
A kind of light-weight Python object with support for member functions.
Useful occassionally for data analysis and rapid prototyping.
"""
 
import functools, collections, operator
 
class AttrDict(dict):
    """
    Python dict with support for member functions.
 
    >>> city = AttrDict()
    >>> city.name = 'Tiny Town'
    >>> city.people = ['Alice', 'Bob', 'Jerry']
    >>> city.population = lambda self: len(self.people)
    >>> city.population()
    3
    >>> city.name
    'Tiny Town'
    """
    def __getattr__(self, attr):
        value = self[attr]
        return functools.partial(value, self) if callable(value) else value
    def __setattr__(self, attr, value):
        self[attr] = value
 
class AttrDefaultDict(collections.defaultdict):
    """
    Python defaultdict with support for member functions.
 
    >>> person = AttrDefaultDict(str)
    >>> def print_full_name(person, prefix): \
            print prefix, person.first_name, person.middle_name, person.last_name
    >>> person.print_full_name = print_full_name
    >>> person.first_name = 'Grant'
    >>> person.last_name = 'Jenks'
    >>> person.print_full_name('Mr.')
    Mr. Grant  Jenks
    """
    def __getattr__(self, attr):
        value = self[attr]
        return functools.partial(value, self) if callable(value) else value
    def __setattr__(self, attr, value):
        self[attr] = value
 
def AttrTree():
    """
    Tree-structure with support for member-like functions.
 
    >>> usa = AttrTree()
    >>> usa.california.capital = 'Sacramento'
    >>> usa.california.abbrev = 'CA'
    >>> usa.california.population = 37e6
    >>> usa.new_york.capital = 'Albany'
    >>> usa.new_york.abbrev = 'NY'
    >>> usa.new_york.population = 19e6
    >>> usa.selector('population')
    56000000.0
    """
    def traverse(tree, func, start=0, accum=operator.add):
        """
        Pre-order traversal of tree.
        Traversal is restricted to "branches" of the tree which are instances
        of dict.
        """
        total = accum(start, func(tree))
        for branch in tree.itervalues():
            if isinstance(branch, dict):
                total = traverse(branch, func, total, accum)
        return total
 
    def selector(tree, name, default=0, start=0, accum=operator.add):
        """
        Field selector for tree branches.
        """
        def helper(node):
            return node[name] if name in node else default
        return traverse(tree, helper, start, accum)
 
    tree = AttrDefaultDict(AttrTree)
    tree.traverse = traverse
    tree.selector = selector
 
    return tree
 
if __name__ == '__main__':
    import doctest
    doctest.testmod()
 
"""
Copyright (c) 2013 Grant Jenks
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
random/python_attribute_dictionary.txt · Last modified: 2013/10/02 00:53 by grant