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.
cannot call function that may raise in a context that cannot raise
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")
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