Search code examples
pythonnamedtuple

Using underscores with namedtuples


I'm working on building a SQL emulator in Python and to store the rows, I'd like to use namedtuples since I can easily handle complex queries with select, order by, and where. I started with normal tuples but I often found myself looking for an attribute of a row and needing to maintain the order of the columns, so I arrived at namedtuples.

The issue is that some of my column names have leading underscores which causes me to end up with ValueError: Field names cannot start with an underscore: '_col2'

I'm looking for either a way to use namedtuples with underscores (maybe some type of override) or a suitable alternative container that allows me to easily convert to a tuple of values in original column order or to access individual values by their field names.

I thought about appending a leading character string to every tuple and then writing a middleware function to serve as the getattr function but by first removing the leading character string - but that seems incredibly hacky.


Solution

  • You can avoid ValueError using rename=True argument

    from collections import namedtuple
    
    a = namedtuple("Table", "_col1 _col2 _col3 col4", rename=True)
    
    print(a._fields)
    

    ('_0', '_1', '_2', 'col4')

    @Edit1 You might want to keep track of which fields have changed

    from collections import namedtuple
    
    columns = "_col1 _col2 _col3 col4"
    a = namedtuple("Table", columns, rename=True)
    
    old_feilds = columns.split()
    new_feilds = a._fields
    
    mapper = {}
    
    for f1,f2 in zip(old_feilds, new_feilds):
        mapper[f1] = f2
    
    print(mapper)
    

    {'_col3': '_2', '_col1': '_0', 'col4': 'col4', '_col2': '_1'}