Function to set component property

I want to write a python function that will set the value of a given property on the component. For example:

def setPropertyValue(component, propertyName, value):
	component.propertyName = value

I have accomplished this using the exec() function:

def setPropertyValue(component, propertyName, value):
	exec('component.%s = value' % propertyName)

Is there any other way of doing this? Is there a method for components that I can use to set the value of a given property?

This works:

def setPropertyValue(component,propertyName,value):
	method = getattr(component,"set%s"% propertyName.title())	
 	method(value)

In this function we get the set method of the property and then call it to set the value.

1 Like

Why wouldn’t one just use python’s setattr() function? Like so:

def setPropertyValue(comp, prop, val):
    setattr(comp, prop, val)

Consider catching AttributeError, though, to fall back on the setPropertyValue() method applicable to custom properties (not always supported by setattr). Like so:

def setPropertyValue(comp, prop, val):
    try:
        setattr(comp, prop, val)
    except AttributeError:
        return comp.setPropertyValue(prop, val)
1 Like

Yes, I like setattr better.

Me too! I was just fighting with this because it was failing with custom properties. Thanks!

In what situation will setattr() not work on custom properties?

When the component is retrieved through Java Swing methods and lists that don’t know about IA’s custom python wrapping, or were python-wrapped before the custom type converter was registered with Py.java2py(). I haven’t exhaustively determined where this applies, so I tend to use the error-checking wrapper everywhere I mix custom and built-in properties. I try to remember to use the methods whenever the relevant code is always accessing a custom property.

If you visit this thread you’ll see that Ignition was not registering its wrapper at all. If you install the release candidate of Simulation Aids posted at the end of that thread, you won’t have to use the getPropertyValue/setPropertyValue methods any more. The python property substitution for custom properties will “just work” in all cases.

1 Like