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
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
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:
It will output "5".
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?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.
Thanks @Melody Daniel !