I am working with a table with lots of columns. In order not to get magic numbers, I code something like this
colName, colID, colDesc = 1, 2, 3
When I want to add a new item, it becomes
#        vvvvvvvv                           v
colName, colAddr, colID, colDesc = 1, 2 ,3, 4
I add in colAddr where I want it and a 4 at the end.  This works with 4 variables but with about 20-30, I get very long lines of code.
So I separated them: one line each
colName = 1
colID = 2
colDesc = 3
If I wish to add something between Name and ID, I would have to renumber the variables which is really painful
colName = 1
colAddr = 2
colID = 3 # renumbered
colDesc = 4 # renumbered
I may have to add columns in between quite often - the table design is still fluid, so I thought of something like this
col = 0
col, colName = col + 1, col
col, colID = col + 1, col
col, colDesc = col + 1, col
If I wanted to add colAddr, then it would just be a one line change
col = 0
col, colName = col + 1, col
col, colAddr = col + 1, col # new line of code
col, colID = col + 1, col
col, colDesc = col + 1, col
This works but looks really messy. Is there a better way of doing this?
If you use a,b,c=range(3) you can add any number of variables at the beginning and change the range value to match the number of variables.
If numbering needs to start at 1 use range(1,4)
You can use collections.namedtuple:
from collections import namedtuple
t = namedtuple('columns', 'colName, colAddr, colID, colDesc')
cols = t._make(range(len(t._fields)))
print(cols)
print(cols.colName)
print(cols.colAddr)
print(cols.colID)
print(cols.colDesc)
Prints:
columns(colName=0, colAddr=1, colID=2, colDesc=3)
0
1
2
3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With