0

I've just started learning Mojo, following the documentation to get started. I've run into a problem with importing the Python module numpy. Below is the code I am using which is taken from the documentation.

from python import Python

fn use_array() raises:
   # This is equivalent to Python's `import numpy as np`
   let np = Python.import_module("numpy")

   # Now use numpy as if writing in Python
   let array = np.array([1, 2, 3])
   print(array)

use_array()

After running this I then receive the following error:

mojo: error: failed to parse the provided Mojo

If I put a try/except statement around the let np = Python.import_module("numpy") it runs, gives the same error with the additional error of:

error: use of unknown declaration 'np',
'fn' declarations require explicit variable declarations
     let array = np.array([1, 2, 3])

I also get this same error when trying to create functions using def() rather than fn(). Finally, I attempted to put use_array() in the fn main() function but to no avail either.

Rather new to this language, but very familiar with Python so if anyone can help it would be greatly appreciated!

M

1 Answer 1

0

to run mojo code locally make sure, for current language stage at least, that you have latest version:

# in case if you on Mac
brew update
brew update modular
modular upgrade mojo

to use python packages:

# make sure this packages installed in your py venv
# or in any other way you manages your virtual environment and packages
python3 -m venv .venv
source .venv/bin/activate

for the code it self, as you noticed you must have main function:

code:

from python import Python

def use_array():
   let np = Python.import_module("numpy")
   let array = np.array([1, 2, 3])
   print(array)

def main():
    use_array()

output:

(.venv)pip install numpy
(.venv)mojo run w.mojo
(.venv)mojo run w.mojo
[1 2 3]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.