I have translated several programs from Python to Nim. Some of them where quite 
simple and the translation was easy… for a human who knows what the program is 
intended for. Other were a bit more complicated, but as these are programs I 
wrote, there is little usage of dynamic features.

In any case, you have to reconstruct types from objects with their attributes 
whose type is unknown and should be retrieved from the context. And if an 
attribute is initialized to None (which may be frequent), you are in trouble. 
You have also to find the type of the functions parameters, if no annotation 
has been provided to help you (and annotations are seldom used). And you have 
to take care of the range of integers as in Python these are big numbers. 
Translating to Nim integers without precautions could lead to some 
disappointments.

For my programs the conversion was possible. But when I tried to convert to Nim 
some libraries I like, I failed. Firstly, I had to find a way to translate 
inheritance, either by using Nim inheritance or using object with variants. 
Then I had to deal with dynamic dispatch, to find a way to transmit methods as 
parameters of other methods (a nightmare). I had also to do a deep 
restructuring as there was cross-references between modules. And I finally gave 
up as there was too much use of dynamic typing.

In fact, it appeared it was impossible to simply translate on a per module 
basis. The right way to proceed would have been to do some retro-engineering to 
get a view of the whole structure, then to write modules from start, the Nim 
way, using existing Python code only to understand the details.

As regards an automatic conversion with a transpiler, I think it would only be 
possible in the most simple cases (i.e. no use of dynamic typing). Even in this 
case, the transpiler would have to find a way to remove the cross-references 
between modules. And it would have to find how to deal with multiple 
inheritance. Even simple inheritance might cause difficulties.

There exist attempts to translate Python code to another language. _Shedskin_ , 
for instance, translates to C++, but with a strong limitation: it can only 
translate pure, but implicitly statically typed Python (2.4-2.6) programs.

There is also _Nuitka_ which translates to C with few limitations, but which 
produces code to link to _libpython_ , the Python runtime. That explains why it 
works. Currently, it doesn’t use the natives types, but the Python types. Of 
course, as it uses the Python runtime, the GIL is still a limitation.

Finally, there is _pypy_ which translates during execution Python code to 
native code with its JIT compiler. But this is something totally different.

Reply via email to