0

I just started to play around with Mojo. I am having a hard time importing modules from the Python standard library even though, according to the examples reported in the quick start guide, importing Python's module should be a breeze. What am I missing?

For example, to import the "time" module, I have tried: let time = Python.import_module("time")

However, I get a couple of errors I don't get.

  1. cannot call function that may raise in a context that cannot raise
  2. use of unknown declaration 'time', 'fn' declarations require explicit variable declarations

I have resolved the first error by adding raises to the function declaration and adding a try/except block to the import line. Although, I am not satisfied with this, it feels too verbose. Is there a better way?

I still don't have a solution for the second error. Can anyone suggest a solution?

fn main() raises:
    #added raises and following try/except block
    #to fix "Error 1"
    
    from python import Python
    try:
        let time = Python.import_module("time")
    except:
        print('Import Error')
        
    let s = time.time() #raises "Error 2"
    print('Hello World')
    let e = time.time()
    print("Done in", e-s, "seconds")

1 Answer 1

1

Here is a working solution. I moved the import python statement outside of the function. I think importing it inside of your main() raises a context error 'somehow' but we're all still learning more about mojo as it develops. Since python was not loaded, the time package was also not loaded which explains why you got error #2.

from python import Python

fn main() raises:
    
    let time = Python.import_module("time")

    let s = time.time()
    print('Hello World')
    let e = time.time()
    
    print("Start (s):", s)
    print("End (s): :", e)
    print("Done in", (e-s), "seconds")

# Hello World
# Start (s): 1695648805.9679005
# End (s): : 1695648805.967926
# Done in 2.5510787963867188e-05 seconds
Sign up to request clarification or add additional context in comments.

4 Comments

Are you running this in a notebook cell or from the terminal?
I ran this from a notebook cell.
Can you try to run it as stand-alone executable instead? I get this error outside the notebook
Your code is correct. It works. Something was probably off with my installation, as the errors disappeared once Mojo was reinstalled.

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.