compas
compas copied to clipboard
Add Tutorial about extending/inheriting from compas classes
Feature Request
As a developer of my own library that inherit from compas class, I want a tutorial showing me how my child class can keep core functionality of the compas class, such as the to_data and from_data functions.
Details
Is your feature request related to a problem? Please describe.
This started as a problem when my Tool class try to inherit the RobotModel class. I would like to keep the to_data and from_data functionality in my child class. Turns out it is not as easy as I thought. With help from @beverlylytle we managed to come up with a working template that allow my Tool class to call the super class's data functions. :
from compas.robots import RobotModel
class Tool(RobotModel):
def __init__(self, name):
super(Tool, self).__init__(name)
self.extra = "Foo"
@property
def data(self):
data = super(Tool, self).data
data.update({'extra': self.extra})
return data
@data.setter
def data(self, data):
super(Tool, self.__class__).data.fset(self, data)
self.extra = data['extra']
def to_data(self):
return self.data
@classmethod
def from_data(cls, data):
tool = Tool(None)
tool.data = data
return tool
if __name__ == "__main__":
from compas.robots import Joint
t = Tool("Name")
t.add_joint("J1", Joint.REVOLUTE , t.add_link("L1"), t.add_link("L2"))
print (t.data)
# Test object creation from data
t2 = Tool.from_data(t.data)
print (t2.data)
# Test copy by data assignment
t3 = Tool(None)
t3.data = t.data
print (t3.data)
I believe other people might want to do the same and this template might be of use. I suggesting adding a page in Docs/Tutorials about Inheriting compas classes, that contain a template for doing this and perhaps other best practice suggestions. Hope this helps someone.
Note
One of the difficulty is to figure out super().data = data doesn't work and has to be super(Tool, self.__class__).data.fset(self, data) as explained in https://stackoverflow.com/questions/10810369/python-super-and-setting-parent-class-property
@yck011522 has this changed with many classes being based on compas.data.Data?
When I posted this issue, there wasn't many classes within compas that implemented data. Now that has changed. However I think the issue of how users (not us, developers) implement the data class still deserves a page in tutorial.
Especially because users are very likely to implement custom classes for serialising their own data.
Makes sense, is json serialization invoked automagically in when invoking compas.rpc.Proxy?
serialisation is indeed invoked automatically on all data classes and other JSON serialisable types. the page about implementing data classes is on the to do list: https://compas.dev/compas/latest/devguide/dtypes.html
@yck011522 is this tied to the #681 issue? That is, if serialization works out well incl meshes, then perhaps that inching towards writing URDF's with meshes?
@jf--- this is not tied to #681 .