SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Rusty Python
Python interpreter, reimagined.
About the dude standing here
● Juhun “RangHo” Lee
● Professional procrastinator
● Commits bullshits for living
● Oh shit another hipster again
Twitter: @RangHo_777
GitHub: @RangHo
I like programming
languages.
Like, a lot.
Rust is pretty cool…… Right?
● Compile-time memory safety
● Zero-cost abstraction
● Fearless concurrency
● Runtime engine not required
● FFI-able design
● Embed-able toolchain
● IT IS THE BEST COMPILED LANGUAGE EVER!!!11!!1!!!!
And Python is quite nice…… Isn’t it?
● Feature-rich standard library
● Partially prototype-based OOP
● (Relatively) Easy metaprogramming
● Multi-paradigm
● Syntax is hip af
● It works on your machine as well™
● IT IS THE BEST SCRIPTING LANGUAGE EVER!!!!!11!!
Imagination time!
● I have a Rust
○ which is hip in and of itself
● I have a Python
○ which used to be hip in and of itself
UH!
● Rust + Python! (or something)
○ which has to be hip af right? SO INTERESTING OMFG
“자, 재밌는 상상 한 번 해 보자고.” - Some random
dude
Heap Hip overflow — how?
● The big question: HOW DO WE DOUBLE THE HIP?
● Two of many ways to achieve hip²
1. Python-based: Building Rust for Python
2. Rust-based: Building Python for Rust
Building Rust for Python
Stage 1
Python ❤️ Extension
● Python can be extended using C or C++
● Extensions - Python function with native code
● Python is slow af
○ Keras
○ TensorFlow
○ PyTorch
○ NumPy
○ SciPy
○ ...anything that requires heavy calculations
Where Python loses its strength…
● C/C++ extension requires...
○ Manual memory management and fun times free()-ing stuff
○ Manual reference counting with Py_INCREF and Py_DECREF macros
○ Saying bye bye to memory safety
“Why bother using Python, when you have C?”
Here comes a new challenger!
● Rust can fix these issues
○ Memory management? -> Leave that to the Borrow Checker™
○ Reference counting? -> Leave that to the Borrow Checker™
○ Memory safety? -> Leave that to the Borrow Checker™
● Make native Python more Python-y!
Sure, but we want the juice of it
● The most important stuff: PERFORMANCE!
● Simple implementation of Sieve of Eratosthenes
Performance Battle (ver. Python)
● Only 11 lines!
● Basically looks like a
pseudocode
○ (and it is basically a
pseudocode)
● It takes about 25ms to sieve
out 100,000 numbers
○ i7-9700K, btw
Performance Battle (ver. C)
● Relatively massive
● Some if statements for memory
safety
○ I forgot malloc safety check as
well
● It takes about 700µs to sieve
out 100,000 numbers
○ Same, i7-9700K
Performance Battle (ver. Rust + PyO3)
● Simpler than the C code
● Resembles Python more
● Requires two functions
○ Usually they are separated
● It takes about 670µs to sieve
out 100,000 numbers
○ Again, i7-9700K
Performance battle result
● Jesus Christ, Python is slow
● In most cases, Rust is as fast as C
● In most cases, Rust requires less memory-related code
=> Rust is enough to replace C for Python extensions!
Building Python for Rust
Stage 2
There are loads of Pythons out there
● CPython - The “Reference”
● PyPy - The Ouroboros of Infinity
● MicroPython - The Featherweight Warrior
● Jython - Python with a cup of coffee
● IronPython - Python got Microsoft’d
Why another one?
“One of the reasons is
that… I wanted to
learn Rust.”
- Windel Bouwman
Learning Rust by making a Python interpreter
● Currently RustPython project has 5M+ lines of code
● In the beginning, it used to be really simple
○ https://github.com/windelbouwman/rspython
● Now it is fully (kinda) functional Python 3.5 interpreter
Yeah, but why?
Let’s pull out the C-equivalent of p[key], where p is dict:
PyObject *PyDict_GetItem(PyObject *p, PyObject *key);
From the dict
object
...find by key...and return the
borrowed reference
Yeah, but why? (Cont’d)
PyObject *PyDict_GetItem(PyObject *p, PyObject *key);
From the dict
object
...find by key...if no match,
return NULL
(no exception)
Yeah, but why? (Cont’d)
Because Python is GC’d language:
PyObject *PyDict_GetItem(PyObject *p, PyObject *key);
Keeps reference
counter of its own
Keeps reference
counter of its own
Keeps reference
counter of its own
Yeah, but why? (Cont’d)
● Here are some Rust features:
○ Rust ships with Borrow Checker to enforce strict borrowing rules.
○ Rust has a type called Result<T, E> to indicate a recoverable error.
○ Rust has a type called Rc to simplify reference counting.
● Sounds familiar yet?
Boy-meets-girl: an all-time classic
● Python interpreter’s benefit
○ Borrow Checker
○ Rust Standard Library
○ Cargo and Rust Packages
○ Memory Safety
○ WebAssembly
● The Holy Grail of Hipness
How RustPython sees Python
RustPython Interpreter
Design
AST
Byte
code
Source
Lexer & Parser
● Python grammar is painful
● Not context-free language
○ i.e. Indentation
● Two ways to solve issue:
1. Parser-lexer feedback loop
2. “Terminalize” indentation
● Possible to form context-free
grammar out of this spec
○ INDENT and DEDENT
○ Lexing rules are not CF
○ Parsing rules can be CF
○ LL(2) parser can be constructed
Compiler
● Python virtual machine only
understands bytecode
● AST to Bytecode
● Bytecode often reside in memory
● py_compile.compile(file)
○ Python2-> ./xxx.pyc
○ Python3-> ./__pycache__/xxx.pyc
Bytecode
● Python bytecode is not standardized
● Bytecode is subject to change
● Yet CPython has pretty comprehensive documents
○ https://docs.python.org/3/library/dis.html
Some remarks about Bytecode
● Python can be used without .py
source code
○ .pyc file has all the info
● Recovery of original source
code possible
○ e.g. DDLC
● Python bytecode is not
optimized well
○ “Python is about having the
simplest, dumbest compiler
imaginable.”
- Guido van Rossum, our Savior
Optimization Checklist
✓ Constant folding
✓ Immutable allocation
optimization
✗ Unused local variable
elimination
✗ Unnecessary intermediate object
elimination
✗ Loop optimization
✗ Tail recursion optimization
✗ ...and pretty much anything
else
RustPython Bytecode
● RustPython does not
produce bytecode file…
○ Say bye to marshal
● Separated into a crate
○ rustpython-bytecode
● Rather simple
architecture
○ no INPLACE_* or
other advanced stuff
● Massive dispatch loop
Virtual Machine
● Reads bytecode, executes the
darn thing
● Keeps track of runtime info
○ Frames
○ Imported modules
○ Settings
○ Context
○ All builtins
Virtual Machine: the good parts
● Honestly bytecode routine is
not fun at all
○ Read byte -> match instruction
-> dispatch -> go back
● The real fun stuff
○ How PyObject is implemented
○ __builtin__ hellfire mess
○ ByRef and ByVal in Python
○ Rust HashMap v. Python __hash__
○ Metaprogramming
Alright, now what?
● Why RustPython instead of CPython?
○ Native WebAssembly support
○ Guaranteed memory safety
○ Clean, readable codebase
○ Lots of things to learn
● Some projects started picking up
○ pyckitup 2D game engine
○ codingworkshops.org educational website
Can it really stand against CPython?
● Native integration is not
working yet
● Still lots of improvements
needed
○ Some features work on 🅱️in
🅱️ows only
○ It targets WASM but...
● Not very optimized
○ around x16 slower than CPython
○ Sub-optimal data structure
design
Final Thoughts
Alright, I know, let’s face it
● Rust is not the best
○ Any *good* programmer can make manageable code
○ Compilation takes eternity
○ Honestly, wtf is borrow checking
○ “OK, here’s langserver, deal with this crap”
○ Static linkage creates bloated binaries
○ Except libc, because reasons
Alright, I know, let’s face it (cont’d)
● Python is not the best
○ Honestly the “scope-by-whitespace” is an unintelligible mess
○ lol no proper threadings
○ Why no switch-case? WHY?
○ async is a function but no, it’s a generator, but still a function
○ Stop using Python2 already goddammit
○ Basically no optimization is made during compilation stage
Bottom line
● Rust can replace C, but cannot replace C++
○ Modern C++ has many features that help managing memories
○ Partial functional programming support is neat
○ Template-based metaprogramming is scalable enough
● Rust has potential
○ Data science
○ Compilation time is getting faster (for real)
○ Still better than golang, no?
Bottom line
● Python has its uses, but nothing more
○ Pseudocode must remain pseudocode
○ Great scripting engine to make simple CLI tools
■ Ruby, no one cares about that language anymore :(
■ “Perl is worse than Python because people wanted it worse.”
■ JavaScript, we don’t want another 120+MB of dependencies
■ Shell Script is useful, but complex logic is painful
● Stop giving Python a life support
○ Python 2 has fallen cold-dead, long live Python 3
○ Stop shoving more features into the poor thing
Still I am a hipster-
wannabe madman.
(Objectively speaking)

Weitere ähnliche Inhalte

Was ist angesagt?

JRuby: Pushing the Java Platform Further
JRuby: Pushing the Java Platform FurtherJRuby: Pushing the Java Platform Further
JRuby: Pushing the Java Platform FurtherCharles Nutter
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
 
Deconstruct 2017: All programmers MUST learn C and Assembly
Deconstruct 2017: All programmers MUST learn C and AssemblyDeconstruct 2017: All programmers MUST learn C and Assembly
Deconstruct 2017: All programmers MUST learn C and Assemblyice799
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoMatt Stine
 
Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Charles Nutter
 
Oktavia Search Engine - pyconjp2014
Oktavia Search Engine - pyconjp2014Oktavia Search Engine - pyconjp2014
Oktavia Search Engine - pyconjp2014Yoshiki Shibukawa
 
Why use JavaScript in Hardware? GoTo Conf - Berlin
Why use JavaScript in Hardware? GoTo Conf - Berlin Why use JavaScript in Hardware? GoTo Conf - Berlin
Why use JavaScript in Hardware? GoTo Conf - Berlin TechnicalMachine
 
My talk on Piter Py 2016
My talk on Piter Py 2016My talk on Piter Py 2016
My talk on Piter Py 2016Alex Chistyakov
 
three.js WebGL library presentation
three.js WebGL library presentationthree.js WebGL library presentation
three.js WebGL library presentationYleisradio
 
How to make the Fastest C# Serializer, In the case of ZeroFormatter
How to make the Fastest C# Serializer, In the case of ZeroFormatterHow to make the Fastest C# Serializer, In the case of ZeroFormatter
How to make the Fastest C# Serializer, In the case of ZeroFormatterYoshifumi Kawai
 
vimshell made other shells legacy
vimshell made other shells legacyvimshell made other shells legacy
vimshell made other shells legacyujihisa
 
A Closer Look at Fonts and Font Rendering System on openSUSE
A Closer Look at Fonts and Font Rendering System on openSUSEA Closer Look at Fonts and Font Rendering System on openSUSE
A Closer Look at Fonts and Font Rendering System on openSUSEFuminobu Takeyama
 
Culerity - Headless full stack testing for JavaScript
Culerity - Headless full stack testing for JavaScriptCulerity - Headless full stack testing for JavaScript
Culerity - Headless full stack testing for JavaScriptThilo Utke
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming languagerobin_sy
 
Beginning python programming
Beginning python programmingBeginning python programming
Beginning python programmingkanteshraj
 
GPU Computing for Data Science
GPU Computing for Data Science GPU Computing for Data Science
GPU Computing for Data Science Domino Data Lab
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonSway Wang
 

Was ist angesagt? (20)

JRuby: Pushing the Java Platform Further
JRuby: Pushing the Java Platform FurtherJRuby: Pushing the Java Platform Further
JRuby: Pushing the Java Platform Further
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
Deconstruct 2017: All programmers MUST learn C and Assembly
Deconstruct 2017: All programmers MUST learn C and AssemblyDeconstruct 2017: All programmers MUST learn C and Assembly
Deconstruct 2017: All programmers MUST learn C and Assembly
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014
 
Oktavia Search Engine - pyconjp2014
Oktavia Search Engine - pyconjp2014Oktavia Search Engine - pyconjp2014
Oktavia Search Engine - pyconjp2014
 
Why use JavaScript in Hardware? GoTo Conf - Berlin
Why use JavaScript in Hardware? GoTo Conf - Berlin Why use JavaScript in Hardware? GoTo Conf - Berlin
Why use JavaScript in Hardware? GoTo Conf - Berlin
 
My talk on Piter Py 2016
My talk on Piter Py 2016My talk on Piter Py 2016
My talk on Piter Py 2016
 
three.js WebGL library presentation
three.js WebGL library presentationthree.js WebGL library presentation
three.js WebGL library presentation
 
How to make the Fastest C# Serializer, In the case of ZeroFormatter
How to make the Fastest C# Serializer, In the case of ZeroFormatterHow to make the Fastest C# Serializer, In the case of ZeroFormatter
How to make the Fastest C# Serializer, In the case of ZeroFormatter
 
vimshell made other shells legacy
vimshell made other shells legacyvimshell made other shells legacy
vimshell made other shells legacy
 
Shell.me
Shell.meShell.me
Shell.me
 
linux_distro
linux_distrolinux_distro
linux_distro
 
A Closer Look at Fonts and Font Rendering System on openSUSE
A Closer Look at Fonts and Font Rendering System on openSUSEA Closer Look at Fonts and Font Rendering System on openSUSE
A Closer Look at Fonts and Font Rendering System on openSUSE
 
Culerity - Headless full stack testing for JavaScript
Culerity - Headless full stack testing for JavaScriptCulerity - Headless full stack testing for JavaScript
Culerity - Headless full stack testing for JavaScript
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming language
 
Beginning python programming
Beginning python programmingBeginning python programming
Beginning python programming
 
GPU Computing for Data Science
GPU Computing for Data Science GPU Computing for Data Science
GPU Computing for Data Science
 
Ready to go
Ready to goReady to go
Ready to go
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Ähnlich wie Rusty Python

Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughgabriellekuruvilla
 
Python: Thanks for the memories
Python: Thanks for the memoriesPython: Thanks for the memories
Python: Thanks for the memoriesDanil Ineev
 
Python Programming1.ppt
Python Programming1.pptPython Programming1.ppt
Python Programming1.pptRehnawilson1
 
AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8Phil Eaton
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsHenry Schreiner
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...Tsundere Chen
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - BasicMosky Liu
 
Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Carlos Miguel Ferreira
 
Number of Computer Languages = 3
Number of Computer Languages = 3Number of Computer Languages = 3
Number of Computer Languages = 3Ram Sekhar
 
Getting Started with PHP Extensions
Getting Started with PHP ExtensionsGetting Started with PHP Extensions
Getting Started with PHP ExtensionsMichaelBrunoLochemem
 
Python in Industry
Python in IndustryPython in Industry
Python in IndustryDharmit Shah
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io
 

Ähnlich wie Rusty Python (20)

Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
Python: Thanks for the memories
Python: Thanks for the memoriesPython: Thanks for the memories
Python: Thanks for the memories
 
Python Programming1.ppt
Python Programming1.pptPython Programming1.ppt
Python Programming1.ppt
 
Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!
 
AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
 
Ruxmon.2015-08.-.proxenet
Ruxmon.2015-08.-.proxenetRuxmon.2015-08.-.proxenet
Ruxmon.2015-08.-.proxenet
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
Python
PythonPython
Python
 
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
 
Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.Python 3.5: An agile, general-purpose development language.
Python 3.5: An agile, general-purpose development language.
 
Why learn python in 2017?
Why learn python in 2017?Why learn python in 2017?
Why learn python in 2017?
 
Number of Computer Languages = 3
Number of Computer Languages = 3Number of Computer Languages = 3
Number of Computer Languages = 3
 
A Python Tutorial
A Python TutorialA Python Tutorial
A Python Tutorial
 
Getting Started with PHP Extensions
Getting Started with PHP ExtensionsGetting Started with PHP Extensions
Getting Started with PHP Extensions
 
Python in Industry
Python in IndustryPython in Industry
Python in Industry
 
An Introduction to PyPy
An Introduction to PyPyAn Introduction to PyPy
An Introduction to PyPy
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 

Kürzlich hochgeladen

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

Rusty Python

  • 2. About the dude standing here ● Juhun “RangHo” Lee ● Professional procrastinator ● Commits bullshits for living ● Oh shit another hipster again Twitter: @RangHo_777 GitHub: @RangHo
  • 4. Rust is pretty cool…… Right? ● Compile-time memory safety ● Zero-cost abstraction ● Fearless concurrency ● Runtime engine not required ● FFI-able design ● Embed-able toolchain ● IT IS THE BEST COMPILED LANGUAGE EVER!!!11!!1!!!!
  • 5. And Python is quite nice…… Isn’t it? ● Feature-rich standard library ● Partially prototype-based OOP ● (Relatively) Easy metaprogramming ● Multi-paradigm ● Syntax is hip af ● It works on your machine as well™ ● IT IS THE BEST SCRIPTING LANGUAGE EVER!!!!!11!!
  • 6. Imagination time! ● I have a Rust ○ which is hip in and of itself ● I have a Python ○ which used to be hip in and of itself UH! ● Rust + Python! (or something) ○ which has to be hip af right? SO INTERESTING OMFG “자, 재밌는 상상 한 번 해 보자고.” - Some random dude
  • 7. Heap Hip overflow — how? ● The big question: HOW DO WE DOUBLE THE HIP? ● Two of many ways to achieve hip² 1. Python-based: Building Rust for Python 2. Rust-based: Building Python for Rust
  • 8. Building Rust for Python Stage 1
  • 9. Python ❤️ Extension ● Python can be extended using C or C++ ● Extensions - Python function with native code ● Python is slow af ○ Keras ○ TensorFlow ○ PyTorch ○ NumPy ○ SciPy ○ ...anything that requires heavy calculations
  • 10. Where Python loses its strength… ● C/C++ extension requires... ○ Manual memory management and fun times free()-ing stuff ○ Manual reference counting with Py_INCREF and Py_DECREF macros ○ Saying bye bye to memory safety “Why bother using Python, when you have C?”
  • 11. Here comes a new challenger! ● Rust can fix these issues ○ Memory management? -> Leave that to the Borrow Checker™ ○ Reference counting? -> Leave that to the Borrow Checker™ ○ Memory safety? -> Leave that to the Borrow Checker™ ● Make native Python more Python-y!
  • 12. Sure, but we want the juice of it ● The most important stuff: PERFORMANCE! ● Simple implementation of Sieve of Eratosthenes
  • 13. Performance Battle (ver. Python) ● Only 11 lines! ● Basically looks like a pseudocode ○ (and it is basically a pseudocode) ● It takes about 25ms to sieve out 100,000 numbers ○ i7-9700K, btw
  • 14. Performance Battle (ver. C) ● Relatively massive ● Some if statements for memory safety ○ I forgot malloc safety check as well ● It takes about 700µs to sieve out 100,000 numbers ○ Same, i7-9700K
  • 15. Performance Battle (ver. Rust + PyO3) ● Simpler than the C code ● Resembles Python more ● Requires two functions ○ Usually they are separated ● It takes about 670µs to sieve out 100,000 numbers ○ Again, i7-9700K
  • 16. Performance battle result ● Jesus Christ, Python is slow ● In most cases, Rust is as fast as C ● In most cases, Rust requires less memory-related code => Rust is enough to replace C for Python extensions!
  • 17. Building Python for Rust Stage 2
  • 18. There are loads of Pythons out there ● CPython - The “Reference” ● PyPy - The Ouroboros of Infinity ● MicroPython - The Featherweight Warrior ● Jython - Python with a cup of coffee ● IronPython - Python got Microsoft’d Why another one?
  • 19. “One of the reasons is that… I wanted to learn Rust.” - Windel Bouwman
  • 20. Learning Rust by making a Python interpreter ● Currently RustPython project has 5M+ lines of code ● In the beginning, it used to be really simple ○ https://github.com/windelbouwman/rspython ● Now it is fully (kinda) functional Python 3.5 interpreter
  • 21. Yeah, but why? Let’s pull out the C-equivalent of p[key], where p is dict: PyObject *PyDict_GetItem(PyObject *p, PyObject *key); From the dict object ...find by key...and return the borrowed reference
  • 22. Yeah, but why? (Cont’d) PyObject *PyDict_GetItem(PyObject *p, PyObject *key); From the dict object ...find by key...if no match, return NULL (no exception)
  • 23. Yeah, but why? (Cont’d) Because Python is GC’d language: PyObject *PyDict_GetItem(PyObject *p, PyObject *key); Keeps reference counter of its own Keeps reference counter of its own Keeps reference counter of its own
  • 24. Yeah, but why? (Cont’d) ● Here are some Rust features: ○ Rust ships with Borrow Checker to enforce strict borrowing rules. ○ Rust has a type called Result<T, E> to indicate a recoverable error. ○ Rust has a type called Rc to simplify reference counting. ● Sounds familiar yet?
  • 25. Boy-meets-girl: an all-time classic ● Python interpreter’s benefit ○ Borrow Checker ○ Rust Standard Library ○ Cargo and Rust Packages ○ Memory Safety ○ WebAssembly ● The Holy Grail of Hipness
  • 26. How RustPython sees Python RustPython Interpreter Design AST Byte code Source
  • 27. Lexer & Parser ● Python grammar is painful ● Not context-free language ○ i.e. Indentation ● Two ways to solve issue: 1. Parser-lexer feedback loop 2. “Terminalize” indentation ● Possible to form context-free grammar out of this spec ○ INDENT and DEDENT ○ Lexing rules are not CF ○ Parsing rules can be CF ○ LL(2) parser can be constructed
  • 28. Compiler ● Python virtual machine only understands bytecode ● AST to Bytecode ● Bytecode often reside in memory ● py_compile.compile(file) ○ Python2-> ./xxx.pyc ○ Python3-> ./__pycache__/xxx.pyc
  • 29. Bytecode ● Python bytecode is not standardized ● Bytecode is subject to change ● Yet CPython has pretty comprehensive documents ○ https://docs.python.org/3/library/dis.html
  • 30. Some remarks about Bytecode ● Python can be used without .py source code ○ .pyc file has all the info ● Recovery of original source code possible ○ e.g. DDLC ● Python bytecode is not optimized well ○ “Python is about having the simplest, dumbest compiler imaginable.” - Guido van Rossum, our Savior Optimization Checklist ✓ Constant folding ✓ Immutable allocation optimization ✗ Unused local variable elimination ✗ Unnecessary intermediate object elimination ✗ Loop optimization ✗ Tail recursion optimization ✗ ...and pretty much anything else
  • 31. RustPython Bytecode ● RustPython does not produce bytecode file… ○ Say bye to marshal ● Separated into a crate ○ rustpython-bytecode ● Rather simple architecture ○ no INPLACE_* or other advanced stuff ● Massive dispatch loop
  • 32. Virtual Machine ● Reads bytecode, executes the darn thing ● Keeps track of runtime info ○ Frames ○ Imported modules ○ Settings ○ Context ○ All builtins
  • 33. Virtual Machine: the good parts ● Honestly bytecode routine is not fun at all ○ Read byte -> match instruction -> dispatch -> go back ● The real fun stuff ○ How PyObject is implemented ○ __builtin__ hellfire mess ○ ByRef and ByVal in Python ○ Rust HashMap v. Python __hash__ ○ Metaprogramming
  • 34. Alright, now what? ● Why RustPython instead of CPython? ○ Native WebAssembly support ○ Guaranteed memory safety ○ Clean, readable codebase ○ Lots of things to learn ● Some projects started picking up ○ pyckitup 2D game engine ○ codingworkshops.org educational website
  • 35. Can it really stand against CPython? ● Native integration is not working yet ● Still lots of improvements needed ○ Some features work on 🅱️in 🅱️ows only ○ It targets WASM but... ● Not very optimized ○ around x16 slower than CPython ○ Sub-optimal data structure design
  • 37. Alright, I know, let’s face it ● Rust is not the best ○ Any *good* programmer can make manageable code ○ Compilation takes eternity ○ Honestly, wtf is borrow checking ○ “OK, here’s langserver, deal with this crap” ○ Static linkage creates bloated binaries ○ Except libc, because reasons
  • 38. Alright, I know, let’s face it (cont’d) ● Python is not the best ○ Honestly the “scope-by-whitespace” is an unintelligible mess ○ lol no proper threadings ○ Why no switch-case? WHY? ○ async is a function but no, it’s a generator, but still a function ○ Stop using Python2 already goddammit ○ Basically no optimization is made during compilation stage
  • 39. Bottom line ● Rust can replace C, but cannot replace C++ ○ Modern C++ has many features that help managing memories ○ Partial functional programming support is neat ○ Template-based metaprogramming is scalable enough ● Rust has potential ○ Data science ○ Compilation time is getting faster (for real) ○ Still better than golang, no?
  • 40. Bottom line ● Python has its uses, but nothing more ○ Pseudocode must remain pseudocode ○ Great scripting engine to make simple CLI tools ■ Ruby, no one cares about that language anymore :( ■ “Perl is worse than Python because people wanted it worse.” ■ JavaScript, we don’t want another 120+MB of dependencies ■ Shell Script is useful, but complex logic is painful ● Stop giving Python a life support ○ Python 2 has fallen cold-dead, long live Python 3 ○ Stop shoving more features into the poor thing
  • 41. Still I am a hipster- wannabe madman. (Objectively speaking)

Hinweis der Redaktion

  1. P