0

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 instances of the rsyslog daemon (this_instance_number), and many attributes (attribute) defined in a configuration file.

With those value I populate the object.

Given the following variables:

this_instance_number=5
attribute="startupscript"

The following line of code,

print ('rsyslog.instance%(instance_number)s.%(attribute)s' %\
      {"instance_number": this_instance_number, "attribute": attribute})

will print this text:

rsyslog.instance5.startupscript

How can I then assign the attribute that text would refer to to a value based on that format string?

For example, if hard coded, I would assign:

rsyslog.instance5.startupscript="/etc/init.d/sample"

But, I want to assign it something like this:

('rsyslog.instance%(instance_number)s.%(attribute)s' %\
      {"instance_number": this_instance_number, "attribute": attribute}) = variable

1 Answer 1

2

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

instance = getattr(rsyslog, 'instance{}'.format(this_instance_number))
print getattr(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:

def get_deep_attr(obj, *path):
    return reduce(getattr, path, obj)

def set_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)
Sign up to request clarification or add additional context in comments.

3 Comments

Martijn, how then do we populate deeper objects? If I need to edit my original question I will. In a nutshell I'm looping to create rsyslog.<instance#>, and within that loop looping to create the rsyslog.<instance#>.<attribute>s. Your setattr appears to be setting the object's attribute back to whatever you just read, but I will be setting unique values. Is it possible to use settattr like this?: setattr(rsyslog, instance5.startupscript, "/etc/init.d/sample")? By extension then how do we replace "instance5.startupscript" dynamically?
@JustinHaynes: updated with a generic approach to allow for arbitrary-depth attribute chains.
@JustinHaynes: the original approach will still work just fine though, you must've futzed some variable somewhere in your loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.