Skip to content Skip to sidebar Skip to footer

How To Use String Formatting To Dynamically Assign Variables

In Python, I am populating an object to model the configuration, environment and other aspects related to rsyslog on the local machine (RHEL 6.4 Python 2.6.4) I loop through many

Solution 1:

You'd use getattr() to dynamically retrieve attributes:

instance = getattr(rsyslog, 'instance{}'.format(this_instance_number))
printgetattr(instance, attribute)

and setattr() to assign:

instance = getattr(rsyslog, 'instance{}'.format(this_instance_number))
setattr(instance, attribute, variable)

or, for a more generic approach with arbitrary depth:

defget_deep_attr(obj, *path):
    return reduce(getattr, path, obj)

defset_deep_attr(obj, value, *path)
    setattr(get_deep_attr(obj, path[:-1]), path[-1], value)

print get_deep_attr(rsyslog, 'instance{}'.format(this_instance_number), attribute)
set_deep_attr(rsyslog, variable, 'instance{}'.format(this_instance_number), attribute)

Post a Comment for "How To Use String Formatting To Dynamically Assign Variables"