SlideShare a Scribd company logo
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)

More Related Content

What's hot

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 go
Dvir 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 Assembly
ice799
 
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
Matt 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 2014
Charles 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 2016
Alex Chistyakov
 
three.js WebGL library presentation
three.js WebGL library presentationthree.js WebGL library presentation
three.js WebGL library presentation
Yleisradio
 
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
Yoshifumi Kawai
 
vimshell made other shells legacy
vimshell made other shells legacyvimshell made other shells legacy
vimshell made other shells legacy
ujihisa
 
Shell.me
Shell.meShell.me
linux_distro
linux_distrolinux_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
Fuminobu 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 JavaScript
Thilo Utke
 
Rust system programming language
Rust system programming languageRust system programming language
Rust system programming language
robin_sy
 
Beginning python programming
Beginning python programmingBeginning python programming
Beginning python programming
kanteshraj
 
GPU Computing for Data Science
GPU Computing for Data Science GPU Computing for Data Science
GPU Computing for Data Science
Domino Data Lab
 
Ready to go
Ready to goReady to go
Ready to go
Atin Mukherjee
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonSway Wang
 

What's hot (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
 

Similar to Rusty Python

Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
gabriellekuruvilla
 
Python: Thanks for the memories
Python: Thanks for the memoriesPython: Thanks for the memories
Python: Thanks for the memories
Danil Ineev
 
Python Programming1.ppt
Python Programming1.pptPython Programming1.ppt
Python Programming1.ppt
Rehnawilson1
 
AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8
Phil Eaton
 
Introduction to Python
Introduction to PythonIntroduction to Python
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
Henry 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 2016
maiktoepfer
 
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 - Basic
Mosky 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
 
Why learn python in 2017?
Why learn python in 2017?Why learn python in 2017?
Why learn python in 2017?
Karolis Ramanauskas
 
Number of Computer Languages = 3
Number of Computer Languages = 3Number of Computer Languages = 3
Number of Computer Languages = 3
Ram Sekhar
 
A Python Tutorial
A Python TutorialA Python Tutorial
A Python Tutorial
Kartik Singhal
 
Getting Started with PHP Extensions
Getting Started with PHP ExtensionsGetting Started with PHP Extensions
Getting Started with PHP Extensions
MichaelBrunoLochemem
 
Python in Industry
Python in IndustryPython in Industry
Python in Industry
Dharmit Shah
 
An Introduction to PyPy
An Introduction to PyPyAn Introduction to PyPy
An Introduction to PyPy
Michael Hudson-Doyle
 
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
Mender.io
 

Similar to 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
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 

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)

Editor's Notes

  1. P