Are Type Hints Still Possible in Mojo?

Hi all - I was wondering, is there a way to write a def function in Mojo that uses type hints like in Python 3? For example I tried writing this earlier. I'm guessing it's not the right approach though, as the compiler gives a warning that cannot use a dynamic value in type specification
from python import Python

def outer_func():
try:
let PythonInt = Python.import_module("typing").Int

def inner_func(x: Int): # this gives the error
...
except:
pass
from python import Python

def outer_func():
try:
let PythonInt = Python.import_module("typing").Int

def inner_func(x: Int): # this gives the error
...
except:
pass
Although in this case, I suppose it'd be a better idea to use the built-in Int type, to let others know what kind of value x is expecting?
4 Replies
vmois
vmois11mo ago
Types in Python are only hints (hence "type hints" name), effectively Python interpreter ignores them. If you add types in Python you can still put any value you want to the function. Python will happily run it. Could you explain please about what you are trying to accomplish by using Python type hints in Mojo? Def function in Mojo supports types. You can specify them the same way you do in Python, but using types available in Mojo. The only difference is that Mojo will actually respect types. Example:
def func():
def func2(x: Int):
return x + 2
return func2(3)


def main():
print(func())
def func():
def func2(x: Int):
return x + 2
return func2(3)


def main():
print(func())
It will output "5".
Zain Raza (he/him)
Zain Raza (he/him)OP11mo ago
OK, makes sense. What sparked my question is I was wondering how to refactor an existing Python codebase to Mojo. E.g., if my team is currently maintaining a Python codebase, where all the functions use type hints (from typing or our own classes) - does this mean we need to get rid of all the type hints that use typing (e.g., typing.List), if we were to decide to move to Mojo at first, because they wouldn't be recognized as types?
Melody Daniel
Melody Daniel11mo ago
In the future, Mojo will add support for annotating with Python types, and if I understand correctly the compiler will ignore this so it'll behave like Python's type hints.
Zain Raza (he/him)
Zain Raza (he/him)OP11mo ago
Thanks @Melody Daniel !
Want results from more Discord servers?
Add your server