Search code examples
pythontupleskinterbasdb

Creating named tuple from tuple?


I'm working with kinterbasdb to select and update some data from databases of 1998 (yes, unfortunatly :(). And the API of kinterbasdb return the values from queries in tuples, for example:

connection = connect(dsn="database.gdb", user="MYUSER", password="MYPASSWORD")
cursor = connection.cursor()
cursor.execute("SELECT * FROM TABLE_X")
result = cursor.fetchone() # tuple => (value1, value2, value3, value4, value5)

And i would like to map this tuple to a named tuple. Is it possible?

I'm using Python 2.7.13 (i was able to update the kinterbasdb module to make it work... at least)


Solution

  • Just pass your tuple to the namedtuple constructor as expanded args using *.

    In [1]: from collections import namedtuple
    
    In [2]: Response = namedtuple('Response', ['thing1', 'thing2', 'thing3', 'thing4'])
    
    In [3]: mytuple = (1, 2, 3, 4)
    
    In [4]: Response(*mytuple)
    Out[4]: DBResponse(thing1=1, thing2=2, thing3=3, thing4=4)