Skip to content

getattr(myclass,key) not working if key changes #223

Description

@simplynail

I'm doing a 'DataWarehouse' from multiple MS Excel files. From each workbook I get separate "tables_data" that I then add to the database to proper tables.
I get error when referring to dynamically assigned attribute_name via getattr, it looks like it uses old/previous value of attribute_name

Here's models declaration:

class MyClass1(db.Entity):
    _table_ = 'table_name1'

    id = orm.PrimaryKey(int, auto=True)
    name = orm.Required(str, nullable=True)
    other_attr = orm.Required(str, nullable=True)

class MyClass2(db.Entity):
    _table_ = 'table_name2'

    id = orm.PrimaryKey(int, auto=True)
    number = orm.Required(str, nullable=True)
    other_attr = orm.Required(str, nullable=True)

class MyClass3(db.Entity):
    _table_ = 'table_name3'

    id = orm.PrimaryKey(int, auto=True)
    number = orm.Required(str, nullable=True)
    other_attr = orm.Required(str, nullable=True)

and app code is:

detail_classes = [myClass1, myClass2, myClass3]
tables_data = {'table_name1':
                        [{'name':'xy','other_attr':'some_value1'},
                         {'name':'yz','other_attr':'some_value2'}],
                   'table_name2':
                        [{'number':'ab','other_attr':'some_value3'},
                         {'number':'bc','other_attr':'some_value4'}],
                   'table_name3':
                        [{'number':'hi','other_attr':'some_value5'},
                         {'number':'ij','other_attr':'some_value6'}]}

for cls_template in detail_classes:
            # select data for current class template
            data = tables_data[cls_template._table_] 
            # set column name that is unique for current dict
            if cls_template._table_ != 'table_name1':
                key = 'name'
            else:
                key = 'number'

so when I do:
selected = list(cls_template.select(lambda c: getattr(c, key) == row[key]))

I get:
AttributeError: Entity MyClass2 does not have attribute name: getattr(c, key)

Even though current key == 'number'

Metadata

Metadata

Assignees

Labels

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions