How to make use of getter and setter for properties created using createProperty

Hello,
I have a hard time figuring out how to use getter and setter for properties that are created using createProperty. I have originally thought it might be possible to use standard property decorators like in following example (but now I guess it doesn’t make sense this way).

class TestExt:
	def __init__(self, ownerComp):
		self.ownerComp = ownerComp
		TDF.createProperty(self, 'head', value=0, dependable=True, readOnly=False)

	@property
	def head(self):
		print('getter')
		return self._head
	
	@head.setter
	def head(self, value):
		print('setter')
		self._head.val = value

Then I thought I might explicitly specify both getter and setter without use of decorators, but it doesn’t seem to work either.

class TestExt:
	def __init__(self, ownerComp):
		self.ownerComp = ownerComp
		TDF.createProperty(self, 'head', value=0, dependable=True, readOnly=False)
		self.head.getter(self.get_head)
		self.head.setter(self.set_head)

	def get_head(self):
		print('getter')
		return self._head
	
	def set_head(self, value):
		print('setter')
		self._head.val = value

Therefore I have decided not to use createProperty (for the time being) and have rather written it like this. It seems to work as expected, but if anyone knows how to do this with createProperty, I would be happy to use it :slight_smile: Thanks

class TestExt:
	def __init__(self, ownerComp):
		self.ownerComp = ownerComp
		self._head = tdu.Dependency(0)

	@property
	def head(self):
		return self._head
	
	@head.setter
	def head(self, value):
		self._head.val = value

Soo, here is a little trick.
Methods that depend on a dependable value are also dependable. So, yeah, this works:


class Test:
	"""
	Test description
	"""
	def __init__(self, ownerComp):
		# The component to which this extension is attached
		self.ownerComp = ownerComp

		self._Foo = tdu.Dependency(2)


	@property
	def Foo(self):
		return self._Foo.val * 2

	@Foo.setter
	def Foo(self, val):
		self._Foo.val = val

Works also with Channels, Pars, Cells etc.

1 Like

createProperty is a utility function that just does what @alphamoonbase is doing (and some other stuff). You are not meant to create your own getters and setters when using that. If you want custom getters and setters, build them yourself and don’t use createProperty. The code above is a great place to start.

If you’d like to see the code for createProperty, you can find it in /sys/TDModules/TDFunctions. It’s more complicated than doing it with decorators. It’s also not necessary to understand how it works, but if you’re curious, have a look!

Aha, I see, thank you very much for info :slight_smile: