Exemple #1
0
def getSize(obj):
    """Calculate the size as cheap as possible
    """
    # Try the cheap variants first.
    # Actually the checks ensure the code never fails but beeing sure
    # is better.
    try:
        # check if to return zero (length is zero)
        if len(obj) == 0:
            return 0
    except:
        pass
        
    try:
        # check if ``IStreamableReference``
        if IStreamableReference.isImplementedBy(obj):
            size = obj.getSize()
            if size is not None:
                return size
    except:
        pass
        
    try:
        # string
        if isinstance(obj, types.StringTypes):
            return len(obj)
    except:
        pass
        
    try:
        # file like object
        methods = dir(obj)
        if "seek" in methods and "tell" in methods:
            currentPos = obj.tell()
            obj.seek(0, 2)
            size = obj.tell()
            obj.seek(currentPos)
            return size
    except:
        pass
    
    try:
        # fallback: pickling the object
        stream = StringIO()
        p = Pickler(stream, 1)
        p.dump(obj)
        size = stream.tell()
    except:
        size = None
    
    return size