'Add a variable to the method call path in Python

Can you please tell me how to add a variable to the method call path?

Example, i have: 
    my_template = templates.rows.VARS_system.safe_substitute(**service.to_dict())

I want to substitute the value of the variable instead of the word VARS:

my_template = templates.rows.PROD_system.safe_substitute(**service.to_dict())
....
my_template = templates.rows.STAGE_system.safe_substitute(**service.to_dict())


Solution 1:[1]

You could use getattr while looping through a list of names. It will depend on the type of templates.rows, but from the little amount of code given, this might work.

(Untested!)

sections = ['PROD', 'STAGE']

for section in sections:
    name = section + '_system'
    attr = getattr(templates.rows, name)
    my_template = attr.safe_substitute(**service.to_dict())
    # Do stuff with my_template

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 9769953