Python to Julia conversion

Can someone tell me how to convert a python code to julia, i.e., .py to .jl.

This heavily depends on your code. Sometimes it’s enough to change a little syntax, sometimes a rewrite will produce much better and more idiomatic code.
In case there is a misunderstanding here: there is no automatic way to do this, it has to be done by hand.

Do you have an example of code you want to translate?


I don’t think there are any tools to do this automatically for you if that is what you wanted. You would pretty much have to look at the Python code and write the translation to Julia yourself.

1 Like

For calling Python from Julia there is of course the excellent
However there is also by @thautwarm, which transpiles Python code to Julia. It doesn’t support all of Python syntax though, and doesn’t directly output Julia code but I guess that would be relatively easy to add.

But perhaps it would be nice to have a package that does some of the find and replace work for you already. Even if it doesn’t generate valid code, it could still save some work. A very simple and not so great start could be:

# some simple find and replace to go partly from python to julia
# assumes that Python code is formatted with black first
pylines = readlines("")

open("file.jl", "w") do io
    for line in pylines
        line = replace(line, r"^def (.+):$" => s"function \1")
        line = replace(line, r"^(\s*)else:$" => s"\1else")
        line = replace(line, r"^(\s*)elif(.+):$" => s"\1elseif\2")
        line = replace(line, r"^(\s*)if(.+):$" => s"\1if\2")
        line = replace(line, r"^(\s*)for(.+):$" => s"\1for\2")
        line = replace(line, "np." => "")
        println(io, line)