Search code examples
pythonvariablessetattributesetattr

python setattr not checking if variable exists


test file:

my_name = ''
my_home_address = ''
my_home_phone = ''

my_office_address = ''
my_office_phone = ''

This another file, lets call it test2

import test

line1 = ['address', 'home', 'tom', 'downtown', '12345']
line1 = ['address', 'office', 'tom', 'uptown', '4567']

my_map = { 'home': ['my_name', 'my_home_address', 'my_home_phone'],
           'office1': ['my_name', 'my_office_address', 'my_office_phone'],
           'office2': ['my_name', 'my_office_address', 'my_office_phone'],
           }

if line1[1] in my_map.keys():
    for position, c_name in enumerate(line1):
        setattr(test, my_map[line1[1]][pos], my_map[line1[1]][pos])

Question: I have test file which has all the fields that save the data e.g.: my_name = '' my_home_address = '' my_home_phone = '' my_office_address = '' my_office_phone = '' etc...

My input is line1 which can have information in different formats but line1[0] and line1[1] is there for sure. line1[1] tells me what address it is. Now depending on line1[1] i will have to populate variables.

Problem I am facing: Since there are hundreds of Fields , sometimes I miss the spelling, Ex: instead of 'my_home_phone' i give it as 'my_hoe_phne' , stil it loads the information in test.my_hoe_phne = 4567 Instead I want it to through error saying that this variable does not exist in test file. How do I achieve that?

"""


Solution

  • Before running setattr, you can do a quick check to see if the attribute exists on the module or not:

    for pos, c_name in enumerate(line1):
        if not hasattr(test, my_map[line1[1]][pos]):
            raise AttributeError(
                'module `test` has no attribute %s' % my_map[line1[1]][pos])
        setattr(test, my_map[line1[1]][pos], my_map[line1[1]][pos])