Seeking Advice on Porting Python Classes to Mojo Structs
I still struggle with how to port Python classes to Mojo structs in the current state of Mojo and seek some help. Here I post a Python class and suggest four ways to port it to Mojo that I came up with. All of them work in this simple example but seem to have some major drawbacks when the class is more complex.
It would be great to get feedback on how you handle this.
Here an example Python class to port to Mojo
4 Replies
Method 1
My first approach would be to forget about superclasses and implement each subclass independently as struct. The obvious drawback is the redundant code.
`
Method 2
To avoid the redundant code in Method 1, we could define a trait and an implementation of it for the redundant code.
`
Method 3
This would come closest to subclasses in my opinion, by having a trait for the methods which are implemented individually by the subclasses, and injecting them at compile time. One drawback would be that each method call must transfer all the needed data. (inout ...)
`
Method 4
Similar to Method 3 but holding the data in the individual structs.
All of these methods work, but I am not really satisfied with any of them. Right now, I'm leaning towards Method 1, as embarrassing as that might be 😜.
I understand that Mojo will have the required language features at one point. Big question for me right now, is it too early to port projects from Python which make use of classes ...
The proper solution.
In the future when trait supports default methods and fields the following would just work:
Thanks a lot @Ethan , this is as very elagant way of implementing it, very helpful. Yes fields and default methods for traits would enable more straigt forward implementations, but your solution is for what we can do now the best i saw so far. Thanks again
My pleasure. This is the de facto way to achieve polymorphism with traits. I am glad you got the hang of it.