Calling Python from Mojo
The Python ecosystem is full of useful libraries, so you shouldn't have to rewrite them in Mojo. Instead, you can simply import Python packages and call Python APIs from Mojo. The Python code runs in a standard Python interpreter (CPython), so your existing Python code doesn't need to change.
Import a Python module in Mojo
To import a Python module in Mojo, just call
Python.import_module()
with the module name. The following shows an example of importing the standard
Python NumPy package:
from python import Python
def main():
# This is equivalent to Python's `import numpy as np`
np = Python.import_module("numpy")
# Now use numpy as if writing in Python
array = np.array(Python.list(1, 2, 3))
print(array)
from python import Python
def main():
# This is equivalent to Python's `import numpy as np`
np = Python.import_module("numpy")
# Now use numpy as if writing in Python
array = np.array(Python.list(1, 2, 3))
print(array)
Running this program produces the following output:
[1 2 3]
[1 2 3]
Assuming that you have the NumPy package installed in your environment, this imports NumPy and you can use any of its features.
A few things to note:
-
The
import_module()
method returns a reference to the module in the form of aPythonObject
wrapper. You must store the reference in a variable and then use it as shown in the example above to access functions, classes, and other objects defined by the module. See Mojo wrapper objects for more information about thePythonObject
type. -
Currently, you cannot import individual members (such as a single Python class or function). You must import the whole Python module and then access members through the module name.
-
Mojo doesn't yet support top-level code, so the
import_module()
call must be inside another method. This means you may need to import a module multiple times or pass around a reference to the module. This works the same way as Python: importing the module multiple times won't run the initialization logic more than once, so you don't pay any performance penalty. -
import_module()
may raise an exception (for example, if the module isn't installed). If you're using it inside anfn
function, you need to either handle errors (using atry/except
clause), or add theraises
keyword to the function signature. You'll also see this when calling Python functions that may raise exceptions. (Raising exceptions is much more common in Python code than in the Mojo standard library, which limits their use for performance reasons.)
Import a local Python module
If you have some local Python code you want to use in Mojo, just add the directory to the Python path and then import the module.
For example, suppose you have a Python file named mypython.py
:
import numpy as np
def gen_random_values(size, base):
# generate a size x size array of random numbers between base and base+1
random_array = np.random.rand(size, size)
return random_array + base
import numpy as np
def gen_random_values(size, base):
# generate a size x size array of random numbers between base and base+1
random_array = np.random.rand(size, size)
return random_array + base
Here's how you can import it and use it in a Mojo file:
from python import Python
def main():
Python.add_to_path("path/to/module")
mypython = Python.import_module("mypython")
values = mypython.gen_random_values(2, 3)
print(values)
from python import Python
def main():
Python.add_to_path("path/to/module")
mypython = Python.import_module("mypython")
values = mypython.gen_random_values(2, 3)
print(values)
Both absolute and relative paths work with
add_to_path()
. For example,
you can import from the local directory like this:
Python.add_to_path(".")
Python.add_to_path(".")
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!