def toobject(thrift, tobj, cls=None):
    """Convert thrift object `tobj` to Python object (with optional type
    `cls`).
    """
    if cls is not None and isinstance(tobj, cls):
        return tobj
    tcls = globals().get(type(tobj).__name__)
    if tcls is not None:
        return tcls.toobject(thrift, tobj, cls=cls)
    if cls is not None:
        return cls(tobj)
    return tobj
