Why can't i declare a variable which does not mutated/change in mojo

243 views Asked by At

why can't i import python code in mojo

from python import Python
let np = Python.import_module("numpy")

this gives me error

/home/kali/hello.mojo:2:30: error: cannot call function that may raise in a context that cannot raise
let np = Python.import_module("numpy")
         ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~
/home/kali/hello.mojo:2:30: note: try surrounding the call in a 'try' block
let np = Python.import_module("numpy")
                             ^
/home/kali/.modular/pkg/packages.modular.com_mojo/bin/mojo: error: failed to parse the provided Mojo

even in the example code of mojo in hello_interop_mojo code:

from python.python import (
    Python,
    _destroy_python,
    _init_python,
)


def main():
    print("Hello Mojo !")
    for x in range(9, 0, -3):
        print(x)
    try:
        Python.add_to_path(".")
        Python.add_to_path("./examples")
        let test_module = Python.import_module("simple_interop")
        test_module.test_interop_func()
    except e:
        print(e.value)
        print("could not find module simple_interop")

i get this error :

Hello Mojo !
9
6
3
An error occurred in Python.
could not find module simple_interop

i am running mojo on wsl ubuntu image

3

There are 3 answers

0
Iliya On

On your first issue

from python import Python
let np = Python.import_module("numpy")

let np = Python.import_module("numpy") has to be called in a function that either has raises or the assignment is in a try ... catch block. Like in this answer.

On the second issue, you need to have simple_interop.py in the same folder where is the code you are executing.

2
Dinux On

According to the Mojo docs, you need to use Python.add_to_path() to specify a path to the module that you want to import. So, the modified code would be:

from python import Python

Python.add_to_path("path/to/module")
let np = Python.import_module("numpy")

For more info: Mojo Docs

0
Laurent B. On

Actually, Mojo can't deal with direct Python importation

Actually there is no way to import python modules on the fly in a Mojo REPL session (terminal) unless you open the Python notebook as follows :

%%python #Open the Python notebook
import numpy as np

print(np.sqrt(10))
3.1622776601683795

enter image description here

Your Python importation

Mojo does not support exceptions actually and that's why you have this error : error: cannot call function that may raise in a context that cannot raise.

Plus, let and var are not used at a global level but inside a defor restrictive fnfunction.

I suggest you use a function instead and, to prevent errors you should add raisesafter that function in your code.

Proposed script:

from python import Python as py

fn main() raises:
    let np = py.import_module("numpy")
    print(np.sqrt(10))

In Visual Studio it works perfectly