0

We know that if we need to define the column names of a table using pytables we can do it by the following way:

class Project(IsDescription):
    alpha = StringCol(20)
    beta  = StringCol(20) 
    gamma = StringCol(20)

where alpha, beta and gamma are the desired column names of the table. But suppose I would like to use a list "ColumnNames_list" which contains the column names as follows: ColumnNames_list[0] = alpha, ColumnNames_list[1] = beta, ColumnNames_list[2] = gamma

Then how should I define the above class "Project"?

I tried with the following:

ColumnNames_list = []
ColumnNames_list[0] = alpha 
ColumnNames_list[1] = beta 
ColumnNames_list[2] = gamma

class Project(IsDescription):
    for i in range (0, 10):
        ColumnNames_list[i] = StringCol(20)  

It's showing the error:

TypeError: Passing an incorrect value to a table column. Expected a Col (or subclass) instance and got: "2". Please make use of the Col(), or descendant, constructor to properly initialize columns.

Zaman
  • 37
  • 8
  • 1
    You don't "declare" variables in python, so that's not your problem. It would help to have more (any?) information on just how your "code is not working". – Scott Hunter Feb 01 '15 at 00:57

1 Answers1

0

Define the variable first outside the loop:

ColumnNames_list = []
for i in range (0, 10):
    ColumnNames_list.append(StringCol(20))

The reason I'm using append() rather than ColumnNames_list[i] = StringCol(20) is because you can't assign to an index that doesn't exist. Trying to assign ColumnNames_list[1] before it exists throws an IndexError.

Mark
  • 90,562
  • 7
  • 108
  • 148