1. Kirill Simonov
  2. pyyaml-legacy

Source

pyyaml-legacy / yaml / klass.py

import new
import re
import __builtin__

class DefaultResolver:
    def resolveType(self, data, typestring):
        assert __builtin__.bool
        if typestring[:2] == "!!":
            typestring = typestring[2:]
        elif typestring[:1] == "!":
            typestring = typestring[1:]

        if "." in typestring:
            classNodes = typestring.split('.')
            classNodes[0] = classNodes[0]

            if '' in classNodes:
                raise "Invalid private type specifier"

            klass = probeModule(classNodes)

            obj = new.instance(klass) 
            if hasMethod(obj, 'from_yaml'):
                return obj.from_yaml(data)
            obj.__dict__ = data
            return obj

        elif type(getattr(__builtin__,typestring)) == type:
            builtinType = getattr(__builtin__, typestring)
            return builtinType(data)

        else:
            raise "Invalide private type secifier"

def probeModule(classNodes):
    classStack = classNodes[:]
    classStack.reverse()
    while True:
        moduleName = classStack.pop()
        module = __import__(moduleName, globals(), locals())

        if hasattr(module, classStack[-1]):
            return loadClass(module, classStack)

        if not classStack:
            raise "Private type resolved to module" 


def loadClass(classObj, classNodes):
    while True:
        nodeName = classNodes.pop()

        if hasattr(classObj, nodeName):
            classObj = getattr(classObj, nodeName)

        else:
            raise "Failed to resolve private type"

        if not classNodes:
            return classObj


def hasMethod(object, method_name):
    try:    
        klass = object.__class__
    except:
        return 0
    if not hasattr(klass, method_name):
        return 0
    method = getattr(klass, method_name)
    if not callable(method):
        return 0
    return 1

def isDictionary(data):
    return isinstance(data, dict)

try:
    isDictionary({})
except:
    def isDictionary(data): return type(data) == type({}) # XXX python 2.1
    
if __name__ == '__main__':
    print isDictionary({'foo': 'bar'})
    try:
        print isDictionary(dict())
        from ordered_dict import OrderedDict
        print isDictionary(OrderedDict())
    except:
        pass