Convert the contents of a string into name of variable

elbertlev at gmail.com elbertlev at gmail.com
Thu Mar 24 16:50:23 EST 2005


TRy db_row does exactly what you want to do. Slower, but more simple:
##############################
#Sequence2Struct.py

class Struct:
    pass

def MakeStruct(seq, names):
    obj = Struct()
    if len(seq) != len(names):
        raise IndexError("seq and names are not the same length")
    for i in range(len(names)):
        obj.__dict__[names[i]] = seq[i]
    return obj

def ExtractNames(t):
    return [item[0] for item in t]


if __name__ == "__main__":
    t = (1, 2, 3)
    n1 = (("A", 1), ("B", 1), ("C", 2))
    n = ExtractNames(n1)
    print n
    s = MakeStruct(t, n)
    print s, s.A, s.B, s.C
    n = ("A", "B")
    s1 = MakeStruct(t, n)
##############################




More information about the Python-list mailing list