M
Modular10mo ago
Zbornak

Py def vs Mojo fn

Hello there, forgive me if this is a stupid question but I am not very familiar with Python. I was reading up on the fact that Mojo accepts both 'dynamic' Python functions as well as safe Mojo functions. It also states that it is important to know both when using Mojo; I just wanted to ask for a use case where a def would be preferable to a fn? Many thanks!
8 Replies
navhkrinn
navhkrinn10mo ago
Def is mostly for keeping python compatibility, it allows python functions to be easily carried over to Mojo. I wouldn't say it is preferable in any situations from perspective of speed and safety. It can be useful if you want to write code without type checks. So the real advantage def brings is ease of coding with less constraints.
Melody Daniel
Melody Daniel10mo ago
It's preferable for those who only know the ease of use and flexibility of Python
Zbornak
ZbornakOP10mo ago
Ah thanks for the responses, I thought that was the case. I was just thrown by the wording (ie. being important to know both). I seem to be getting on fine just understanding and using the fn functions, I much prefer the safety of it all
navhkrinn
navhkrinn10mo ago
Yeah, I would argue that is the best way to go with this. You can learn def in future to be able to understand if someone uses it on a library you end up using but I don't really see any case where you would prefer def over fn from technical standpoint
gamendez98
gamendez9810mo ago
I think the main benefit is to have te posibility to gradually migrate your python code
Zbornak
ZbornakOP9mo ago
Yes you're right, people likely won't adopt Mojo if it breaks all their Python code after promising to be a superset. Luckily though, I have no Python code so I can start relatively fresh!
gabrieldemarmiesse
People doing scientific computing generally (in research) don't want to type their code. So they'll massively use def over fn, even if, for an software development point of view, it's much better to use fn. Different use cases, different tools... When putting their Mojo code in production, then they just need to add types and var, and then turn def into fn, add unit tests and ship it. Which is much easier than to port all of their code to C++
Zbornak
ZbornakOP9mo ago
This is a good point. As I said, coming in with no knowledge of Python and only a little bit of C++, I never considered that aspect
Want results from more Discord servers?
Add your server