Choosing Your Language: Python or Mojo?

ArjanCodes · Beginner ·🌐 Frontend Engineering ·2y ago

Key Takeaways

The video compares and contrasts Python and Mojo, discussing Mojo's features such as static typing, memory safety, and garbage collection, as well as its current limitations and installation requirements. It also covers Mojo's syntax, including the use of the 'FN' keyword for function definitions and the 'VAR' and 'let' keywords for mutable and constant variables.

Full Transcript

if you love using python but you need more performance there are a few options you can buy a really fast really expensive computer which is not ideal you can also use C or rust bindings and code the part that needs more performance in C or rust but that does mean you need to learn new language switch context Etc today I want to talk about another option which is using another programming language altogether but one that looks a lot like python I'm talking about Mojo I'm going to show you how to use Mojo and how different from using plain old Python and I'm also going to share some of my thoughts about using it and well some mixed feelings I have about it before we start if you want to learn more about how to design a piece of software from scratch I have a free guide for you you can get it at ron. c/d design guide It's contains seven steps that I take whenever I design new piece of software and hopefully it helps you avoid some of the mistakes that I made in the past I codesign guide the link is also in the description of this video now let's dive into Mojo Mojo is a relatively new programming language that builds on the syntax of python and adds quite a few different features on top of that it works internally in a different way than python there are quite a few differences there actually and that actually helps it achieve that much higher performance the main difference is that Mojo is actually a compiled language versus python which is interpreted in a sense you can look at mojo as sort of a marriage of python and rust so instead of being interpreted like python is mojo is compiled it has much stronger type safety it supports static typing which makes a lot of sense in a compiled language there is memory safety there's garbage collection it uses a sort of rust style ownership model and I'm going to show you some examples of that later in the video a caveat is that Mojo is still in early development so it's it's not ready for production it's still missing some essential features in fact at the moment it mostly works well on Unix and MAC machines and on Windows you can still use it but you have to use the windows subsystem for Linux also that means that probably features that we have now are going to be removed replaced improved over time so if you're looking for a really stable language Mojo is not what you should use but still it can be fun to take a closer look at mojo as a form of experimentation and exploration here's an example of a basic hello world Mojo script and to run this you can simply type Mojo and then the name of the script assuming of course that you have installed the tool now I did run into a few issues with installing the tool by the way that was related with using p en and picking the right python version and there were some issues with it not being able to find some libraries again it's not production ready so that's kind of how it is but anyway I got it working and this is the result let's take a Clos look at some of the differences with python and some of the features that Mojo has on top of what python offers if you look at the hello world file you see that there's a couple of minor differences like instead of having a def we write FN in front of the function name similar to what we have in Rust also main is the actual entry point of the script so that's the function that's going to be run when you execute the script with python that's not the case you simply write your commands at the root indentation level and then that's going to run of course my best practice that I recommend is that you actually always Define a main function in your script and then call it explicitly so it's clear what the entry point of the script is but in modu this is by default the main function just like in Rust just like python there are types in this case we have strings A and B as strings and this also returns a string so that's the same syntax as with Python's type annotations but these are actually static types so that's an important difference these are checked at compile time another couple of differences in Python we can simply Define a variable like this in Mojo that doesn't work you see we get some sort of error it doesn't know what x is so we need to actually declare it you can do that by writing the VAR keyword in front of the variable name that makes it a mutable variable so you can change the value later for example I can write xal 6 after that but alternatively you can also use the let keyword and then it's constant value and you also see that when we try to assign a value to X then this actually gives us an error that this is not allowed also if you declare functions like this and you have parameters Like A or B in this case you need to supply a type so if I remove this you see that we actually also get an error here because we need to indicate to Mojo what the type is of a otherwise it can compile the code so let's put that back in the function body itself you don't have to supply a type annotation so if I write let's say let my name equals AR I don't need to indicate that my name is actually of type string but of course if you want to you can add a type annotation here it's just not necessary and typically when I Define variables like this I don't include the type annotation unless it's completely unclear what the type is normally you can easily infer it from on the right hand side so there's no need to do it by the way if you like talking about different programming languages their pros and their cons how they affect software design you should definitely check out my free Discord server you can get access by going to discord. ion.co the link is also below a few other things that I want to show you so this is another version of that same hello world example so we still have our main function and I've added a couple of other functions here as well there's a hello function but there's also a python style World function Mojo is in principle compati with python but of course it's a compiled language so there needs to be some kind of boundary between the unsafe messy python world and the memory safe very strict Mojo world and the way Mojo does that is with the exception mechanism here you see an example of that so I have a python style function here called world that's simply going to print world and then when I want to call it I need to put that in a TR accept block so if I turn this into comment like so then you see that now we actually get an error that uh we cannot call function that may raise in a context that we cannot raise so Mojo does these types of checks and that means that if you want to call python function from a Mojo function you need to put it in a try except po like so if you write a python style function like this well that comes at the cost of type safety because python doesn't enforce types and because of that mod you also use the different just in time compilation mechanism in order to compile python code and that's a bit slower than running Mojo code directly so that's something to be aware of here's another example that shows a couple of different things that Mojo offers so again there's a main function at the bottom that's the entry point of the program and then there's a couple of other things here there's a struct and there's a trait so these things look very similar to what we have seen in Rust before so let's go over how this actually works so we have a struct called user similar to what a struct is in Rust there's one difference though you can Define these sorts of functions to be part of the struct and rust you need to use an input for that a struct can have variables so a user in this case has a username and an email you need to declare these with the VAR keywords inside the struct and then we have an initializer with a couple of arguments and we can set the values inside the struct in the initializer and there's a couple of other functions that are added here as well such as this type which means that we can have a string representation of that struct so the struct user implements this stringle trait which simply says that the type can be converted to a string another thing you can see here is value decorator and this simply means that the user struct can be copied and moved around similar to the copy trait in Rust so you may think okay so struct is basically a class well it is slightly different in that there is no inheritance mechanisms for example classes are not yet supported in modjo but that is a pled feature another thing that I'm using here is something called a dynamic vector and this is similar to Python's list you also see we Supply a type of dynamic Vector so this is a vector list of users and then we can depend users to that Dynamic Vector now in order to be able to do that we need to implement the collection element tra that means this user struct is allowed to be part of collections if I remove this then you see we're going to get an error here that this is not allowed because it needs to have the collection element type and finally similar to python we can use a for Loop to go through the list of users now unfortunately if you try this then that doesn't work because dynamic vectors currently doesn't implement the iter method I don't know if they want to add that in the future but that would actually be helpful to have something like that so things like string B collection elements that trades just like in Rust and you can also Define your own trads I have here another trade called emailable that I've defined here at the top so this trade defines two functions get email and send email and then of course if you add the trade then you also need to implement the methods here so if I change these two comments then again we're going to get an error because it doesn't Implement all the requirements for the tradeit so let me put that back so traits are also in the Ross programming language it's sort of comparable to what we have in Python with protocols but of course protocol classes in Python are not enforced at all the simply hints and with languages like rust and moo these are actually enforced and checked when you compile the code a final thing that I want to mention about python compatibility and how you would transition from python to Mojo is that typically like I've shown here in this hello world example you would have your python code in a def function similar to how we would do it in Python and then you put it in a try accept block when you call it from a modo style function so if you want to transition from python to modu to benefit from the higher performance then one way that you can do it in steps is simply call that python code using a tri accept loog and then slowly migrate the functions to Mojo functions at type safety where necessary final thing that I want to to talk about is ownership so this is similar to how rust also manages memory and we have a couple of different keywords in modo to handle ownership so there is inout there is owned and there is borrowed and this indicates who owns the value at any given time and that in turn determines whether the value is actually still needed or can be cleaned up by looking at who owns the value the first option is inout this borrows ownership during the function call and it's also mutable but after that it Returns the ownership so that means that when we run this function we get a self object and we can actually set values in it we can change it that's what in out does if we remove that we get an errow because we're trying to set values in it so this needs to be mutable next to the inout keyword we have the borrowed keyword which is exactly the same as inout except that it's immutable so you can't change the object and before there was a tiny mistake here this actually returns ownership the final keyword that you can use to manage ownership is owned so this actually transfers the ownership of the value from the color of the function to the function itself so now username if it's no longer being used afterwards then the value will be destroyed by the runtime after that by default the parameter of Mojo function is borrowed so if you look at the hello world example that I shown you before so we have the add function so actually A and B they're both borrowed so you don't need to write the borrowed keyword in front of it even though you can if you have a python style function like the function here you add a parameter to that then then by default that parameter is going to be owned so ownership is transferred and that choice that design Choice also has to do with the more Dynamic nature of python so it makes more sense that because python is more Dynamic and we have less control over what happens that we actually transfer the ownership of values when we call python code so I hope these examples gave you an idea of what Mojo is and how it's different from python now currently like I said Mojo is not ready for production so don't use it for Mission critical applications even though it's a nice tool to experiment with and see what is possible it can also help you if you are thinking about moving to rust for example to get a bit of an idea of how things work in an ownership model of memory and then you know maybe later on transition to rust if you find that interesting so there's still several features that need to be implemented that still need to be done and it also means that the syntax may change over time and that if you write a program in Mojo now that in 6 months or a year it may no longer work correctly because things have changed in the meantime also it was kind of finicky to set up at least on my Mac I needed to set paths explicitly run some commands explicitly so it wasn't as easy as just installing Python and then off you go now granted I think most of those issues were related to me using pan but still that's a pretty standard setup for people using python so I think if you introduce a new language like moju you should take that into account and make sure that actually also works in those cases but I did get it working as it should in the end so I'm sure the modu team is working on improving those things as well so final thoughts about this I think Mojo is an intriguing language it's an interesting marriage between Python and rust and they find that intriguing because it gives us an idea of what it could look like if we have a language that sort of marries the best things of Both Worlds both python with its flexibility and simplicity and rust with its types safety performance so am I going to use it personally no it's not yet ready for production yet and when I look at how I use Python actually in most cases by far most cases python is actually perfectly suitable to me and if I really need high performance which is actually kind of rare for me then I think I would first investigate whether I could start using rust more and integrate that into python rust is completely open programming language you don't need to sign up for anything and it's also quickly gaining popularity so I would put my chips on Rust at the moment so the bottom line for me is that Mojo doesn't really solve a problem for me it's a bit too early but that might change in the future who knows now I'd like to hear from you are you using Mojo why are you using it instead of python or Rost or something else what are your thoughts about Mojo let me know in the comments talking about rust if you want to learn more about that I did an introduction video a while back helping pythonistas get started with rust more quickly and you can watch that right here thanks for watching and see you next time

Original Description

💡 Learn how to design great software in 7 steps: https://arjan.codes/designguide. If you're into Python but need better performance, you might consider using Mojo. It's a programming language similar to Python. In this video, I’ll show you how to use it and how it differs from using plain old Python. GitHub repository: https://git.arjan.codes/2024/mojo. 🔥 Modular/Mojo's website: https://www.modular.com/max/mojo. 🎓 ArjanCodes Courses: https://www.arjancodes.com/courses. 💬 Join my Discord server: https://discord.arjan.codes. ⌨️ Keyboard I’m using: https://amzn.to/49YM97v. 🔖 Chapters: 0:00 Intro 1:00 About Mojo 1:45 Installation and Execution 5:14 Segue 11:50 What Mojo is not 13:07 Final thoughts #arjancodes #softwaredesign #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from ArjanCodes · ArjanCodes · 0 of 60

← Previous Next →
1 Full stack WEB DEVELOPMENT in 2021 - the ULTIMATE tech stack for FAST web app development
Full stack WEB DEVELOPMENT in 2021 - the ULTIMATE tech stack for FAST web app development
ArjanCodes
2 FROM PRODUCT IDEA TO SOFTWARE - turn your idea into reality in a few steps
FROM PRODUCT IDEA TO SOFTWARE - turn your idea into reality in a few steps
ArjanCodes
3 Cohesion and Coupling: Write BETTER PYTHON CODE Part 1
Cohesion and Coupling: Write BETTER PYTHON CODE Part 1
ArjanCodes
4 Build a GLASSMORPHISM React Component - Typescript & Material-UI
Build a GLASSMORPHISM React Component - Typescript & Material-UI
ArjanCodes
5 Observer Pattern Tutorial: I NEVER Knew Events Were THIS Powerful 🚀
Observer Pattern Tutorial: I NEVER Knew Events Were THIS Powerful 🚀
ArjanCodes
6 100% CODE COVERAGE - Think You're Done? Think AGAIN.☝
100% CODE COVERAGE - Think You're Done? Think AGAIN.☝
ArjanCodes
7 Two UNDERRATED Design Patterns 💡 Write BETTER PYTHON CODE Part 6
Two UNDERRATED Design Patterns 💡 Write BETTER PYTHON CODE Part 6
ArjanCodes
8 1000 Subscribers! 🚀 WHY I Started this Channel and WHAT'S NEXT
1000 Subscribers! 🚀 WHY I Started this Channel and WHAT'S NEXT
ArjanCodes
9 Channel Trailer ArjanCodes - March 2021
Channel Trailer ArjanCodes - March 2021
ArjanCodes
10 Exception Handling Tips in Python ⚠ Write Better Python Code Part 7
Exception Handling Tips in Python ⚠ Write Better Python Code Part 7
ArjanCodes
11 Monadic Error Handling in Python ⚠ Write Better Python Code Part 7B
Monadic Error Handling in Python ⚠ Write Better Python Code Part 7B
ArjanCodes
12 GW BASIC Games I Wrote When I Was a Kid 🎮 Running 30 Year Old Code
GW BASIC Games I Wrote When I Was a Kid 🎮 Running 30 Year Old Code
ArjanCodes
13 Why You Should Think About SOFTWARE ARCHITECTURE in Python 💡
Why You Should Think About SOFTWARE ARCHITECTURE in Python 💡
ArjanCodes
14 Uncle Bob’s SOLID Principles Made Easy 🍀 - In Python!
Uncle Bob’s SOLID Principles Made Easy 🍀 - In Python!
ArjanCodes
15 QUESTIONABLE Object Creation Patterns in Python 🤔
QUESTIONABLE Object Creation Patterns in Python 🤔
ArjanCodes
16 If You’re Not Using Python DATA CLASSES Yet, You Should 🚀
If You’re Not Using Python DATA CLASSES Yet, You Should 🚀
ArjanCodes
17 CODE ROAST: Yahtzee - New Python Code Refactoring Series!
CODE ROAST: Yahtzee - New Python Code Refactoring Series!
ArjanCodes
18 7 UX Design Tips for Developers
7 UX Design Tips for Developers
ArjanCodes
19 Going All-in on Software Design in Python + an ANNOUNCEMENT 🎙
Going All-in on Software Design in Python + an ANNOUNCEMENT 🎙
ArjanCodes
20 🎙 Interview with Sybren Stüvel, Developer @ Blender 3D
🎙 Interview with Sybren Stüvel, Developer @ Blender 3D
ArjanCodes
21 Do We Still Need Dataclasses? // PYDANTIC Tutorial
Do We Still Need Dataclasses? // PYDANTIC Tutorial
ArjanCodes
22 7 Python Mistakes That Instantly Expose Junior Developers
7 Python Mistakes That Instantly Expose Junior Developers
ArjanCodes
23 Answering Your Most Frequently Asked Python Questions // Q&A 07-2021
Answering Your Most Frequently Asked Python Questions // Q&A 07-2021
ArjanCodes
24 GitHub Copilot 🤖 The Future of Software Development?
GitHub Copilot 🤖 The Future of Software Development?
ArjanCodes
25 More Python Code Smells: Avoid These 7 Smelly Snags
More Python Code Smells: Avoid These 7 Smelly Snags
ArjanCodes
26 Test-Driven Development In Python // The Power of Red-Green-Refactor
Test-Driven Development In Python // The Power of Red-Green-Refactor
ArjanCodes
27 5 Tips To Keep Technical Debt Under Control
5 Tips To Keep Technical Debt Under Control
ArjanCodes
28 Refactoring A Tower Defense Game In Python // CODE ROAST
Refactoring A Tower Defense Game In Python // CODE ROAST
ArjanCodes
29 The Factory Design Pattern is Obsolete in Python
The Factory Design Pattern is Obsolete in Python
ArjanCodes
30 Why the Plugin Architecture Gives You CRAZY Flexibility
Why the Plugin Architecture Gives You CRAZY Flexibility
ArjanCodes
31 Refactoring A Data Science Project Part 1 - Abstraction and Composition
Refactoring A Data Science Project Part 1 - Abstraction and Composition
ArjanCodes
32 Refactoring A Data Science Project Part 2 - The Information Expert
Refactoring A Data Science Project Part 2 - The Information Expert
ArjanCodes
33 Refactoring A Data Science Project Part 3 - Configuration Cleanup
Refactoring A Data Science Project Part 3 - Configuration Cleanup
ArjanCodes
34 Purge These 7 Code Smells From Your Python Code
Purge These 7 Code Smells From Your Python Code
ArjanCodes
35 Running A Software Development YouTube Channel
Running A Software Development YouTube Channel
ArjanCodes
36 Refactoring A PDF And Web Scraper Part 1 // CODE ROAST
Refactoring A PDF And Web Scraper Part 1 // CODE ROAST
ArjanCodes
37 Refactoring A PDF And Web Scraper Part 2 // CODE ROAST
Refactoring A PDF And Web Scraper Part 2 // CODE ROAST
ArjanCodes
38 How To Easily Do Asynchronous Programming With Asyncio In Python
How To Easily Do Asynchronous Programming With Asyncio In Python
ArjanCodes
39 The Software Designer Mindset
The Software Designer Mindset
ArjanCodes
40 NEVER Worry About Data Science Projects Configs Again
NEVER Worry About Data Science Projects Configs Again
ArjanCodes
41 Powerful VSCode Tips And Tricks For Python Development And Design
Powerful VSCode Tips And Tricks For Python Development And Design
ArjanCodes
42 8 Python Coding Tips - From The Google Python Style Guide
8 Python Coding Tips - From The Google Python Style Guide
ArjanCodes
43 What Is Encapsulation And Information Hiding?
What Is Encapsulation And Information Hiding?
ArjanCodes
44 8 Tips For Becoming A Senior Developer
8 Tips For Becoming A Senior Developer
ArjanCodes
45 Building A Custom Context Manager In Python: A Closer Look
Building A Custom Context Manager In Python: A Closer Look
ArjanCodes
46 GraphQL vs REST: What's The Difference And When To Use Which?
GraphQL vs REST: What's The Difference And When To Use Which?
ArjanCodes
47 You Can Do Really Cool Things With Functions In Python
You Can Do Really Cool Things With Functions In Python
ArjanCodes
48 Announcing The Black VS Code Theme (Launching April 1st)
Announcing The Black VS Code Theme (Launching April 1st)
ArjanCodes
49 7 DevOps Best Practices For Launching A SaaS Platform
7 DevOps Best Practices For Launching A SaaS Platform
ArjanCodes
50 Refactoring a Rock Paper Scissors Lizard Spock Game // Code Roast Part 1
Refactoring a Rock Paper Scissors Lizard Spock Game // Code Roast Part 1
ArjanCodes
51 Refactoring a Rock Paper Scissors Lizard Spock Game // Part 2
Refactoring a Rock Paper Scissors Lizard Spock Game // Part 2
ArjanCodes
52 Things Are Going To Change Around Here
Things Are Going To Change Around Here
ArjanCodes
53 Dependency Injection Explained In One Minute // Python Tips
Dependency Injection Explained In One Minute // Python Tips
ArjanCodes
54 How To Setup A MacBook Pro M1 For Software Development
How To Setup A MacBook Pro M1 For Software Development
ArjanCodes
55 A Simple & Effective Way To Improve Python Class Performance
A Simple & Effective Way To Improve Python Class Performance
ArjanCodes
56 How To Write Unit Tests For Existing Python Code // Part 1 of 2
How To Write Unit Tests For Existing Python Code // Part 1 of 2
ArjanCodes
57 How To Write Unit Tests For Existing Python Code // Part 2 of 2
How To Write Unit Tests For Existing Python Code // Part 2 of 2
ArjanCodes
58 Make Sure You Choose The Right Data Structure // Python Tips
Make Sure You Choose The Right Data Structure // Python Tips
ArjanCodes
59 5 Tips For Object-Oriented Programming Done Well - In Python
5 Tips For Object-Oriented Programming Done Well - In Python
ArjanCodes
60 Next-Level Concurrent Programming In Python With Asyncio
Next-Level Concurrent Programming In Python With Asyncio
ArjanCodes

This video teaches viewers how to design software systems using Mojo, a compiled language that builds on Python's syntax, and how to choose between Python and Mojo for their system design needs. It covers Mojo's features, syntax, and limitations, as well as its potential use cases.

Key Takeaways
  1. Install Mojo on a Unix or MAC machine, or use the Windows Subsystem for Linux
  2. Use the 'FN' keyword to define functions in Mojo
  3. Use the 'VAR' and 'let' keywords to declare mutable and constant variables
  4. Use type annotations for function parameters
  5. Use Mojo's exception mechanism to handle errors
  6. Use Mojo's ownership model to manage memory
💡 Mojo's compiled language and ownership model provide a more secure and performant alternative to Python, but it is still in early development and not ready for production.

Related AI Lessons

Chapters (6)

Intro
1:00 About Mojo
1:45 Installation and Execution
5:14 Segue
11:50 What Mojo is not
13:07 Final thoughts
Up next
The masks we wear | Zora Krstić | TEDxLuxembourgCity
TEDx Talks
Watch →