A Python Interpreter Written in Rust
github.com
github.com
Still, no discussion about Python implementations is complete without some mention of the infamous GIL (global interpreter lock). :-) CPython has it, Pypy doesn't (I think) (EDIT: yes it does), Jython doesn't, etc. What is the GIL plan for RustPython?
Jython, as you state, does not: http://www.jython.org/jythonbook/en/1.0/Concurrency.html
https://wiki.python.org/jython/JythonFaq/GeneralInfo
Last commit was over a year ago:
Grumpy was supposed to accomplish the same for Python->Go, and although now abandoned, probably holds some lessons in how to design a platform to help Python projects get Rusted.
Grumpy compiled python code to fairly unreadable Go, and then quickly compiled the result. One effect of this is that a programmer could theoretically refactor the resulting Go code gradually.
I'd love to see a better separation of language and VMs. I think it's a bit sad that a language designer has to either implement their runtime system from scratch, or has to run it on top of a VM that was designed for another language (Java in the case of Jython).
Therefore, the thing I'm looking forward to most is a concurrent, generic and portable VM written in Rust.
Wasn't Perl 6's Parrot kind of meant to fulfil that role?
Yes, that was an original project goal. You can see this as far back as Larry's State of the Onion 2003:
https://www.perl.com/pub/2003/07/16/soto2003.html/
... the "Parrot: Some Assembly Required" article written by Simon Cozens in September 2001:
https://www.perl.com/pub/2001/09/18/parrot.html/
... or, if you trust Git commits rather than articles which could have been edited in the meantime, the same article revised as introductory docs in the Parrot repository in December 2001:
https://github.com/parrot/parrot/blob/9bc8687beb5180e4cc8971...
1. A concurrent garbage collector is 10x more work than a single-threaded one. People often don't realize this.
2. A language-independent VM is 10x more work than a VM for a given language. People often don't realize this this.
In other words, VMs are tightly coupled to the language they implement, unless you make heroic efforts to ensure otherwise.
WebAssembly is a good example of #2. I think the team is doing a great job, but they are inevitably caught between the constraints of different languages (GC, exceptions, etc.)
The recent submission The Early History of F# sheds some light on this with respect to the CLR:
https://news.ycombinator.com/item?id=18874796
An outreach project called “Project 7” was initiated: the aim was to bring seven commercial languages and seven academic languages to target Lightning at launch. While in some ways this was a marketing activity, there was also serious belief and intent. For help with defining the academic languages James Plamondon turned to Microsoft Research (MSR).
I think this is the only way to design a language-independent VM -- port a whole bunch of languages to it. And there are probably 4 or 5 companies in the world with the resources to do this.
I've seen some VM designs that aim to be generic, but since they were never tested, the authors are mistaken about the range of languages they could efficiently support.
Of course, you can always make a language run on a given VM, but making it run efficiently is the main problem.
There is an effort to get the BEAM ported to rust, which would be very exciting.
My own baby, Snigl [0]; doesn't even support preemptive threads, only cooperative multitasking; with a twist, since blocking operations are delegated to a background thread pool while yielding when multitasking.
Also, keep in mind that cooperative multitasking may cause unexpected high latencies, which is unfortunate e.g. in GUI applications and web servers; this is a result of queueing theory, and an example is given here: https://www.johndcook.com/blog/2008/10/21/what-happens-when-...
By the way, on POSIX systems there is a way to schedule background IO operations without even using threads: http://man7.org/linux/man-pages/man7/aio.7.html
From what I know, cooperative multitasking suffers significantly less from unpredictable performance than preemptive threading. The biggest source of uncertainty in Snigl is the preemptive IO loop.
The things is that I really don't feel like writing a concurrent runtime; been there, done that. I'm planning something along the lines of Erlang's processes and channels based on separate interpreters for those scenarios.
They're implemented (in my mind so far) as preemptive threads, one per interpreter; which makes them slightly more heavy-weight than Erlang's NxM and a nice complement to purely cooperative multitasking.
From my limited experience, Erlang doesn't share data between processes; you throw it over the fence by sending to the process inbox, which is where the locking takes place.
Still, shuffling data between OS threads is an easier problem to solve than serializing between OS processes.
Many libraries are not prepared for the disappearance of the GIL and while it's not a general problem for python per se it will be a great amount of work to make every library compatible with GILless python.
Therefore I think that you must always provide an option for the GIL that is enabled by default in order to provide backward compatibility.
This is true, but it doesn't mean that a GIL-less Python would need to have an option for "enable GIL so I don't have to worry about data races". It means that a GIL-less Python would have to ensure that there are no data races, without having to have a GIL.
> it will be a great amount of work to make every library compatible with GILless python
No, it won't; libraries won't have to change at all. The current interpreter makes a guarantee that those libraries rely on: "you don't have to worry about data races". A GIL-less interpreter would have to make the same guarantee; it just wouldn't have to have a GIL to do it. That requirement is what makes a GIL-less Python interpreter hard to do.
Other languages achieve a good compromise by clustering data structures into fewer parts with only a handful of mutexes that are locked while other threads work on different datasets. This is usually done manually and with great care as it is the heart of both safety and performance. I don't know if there is an automatic solution to this problem that is compatible with the way python programs are structured.
The libraries basically assume that, while you call them, nothing else changes. In order to ensure that you need to lock everything down. Because you don't know what these libraries do and what data they access it needs to be everything (like it is today). It should be possible to only lock the GIL when such a library is called, so there should be kind of a middle way forward.
So in practice I don't think it simplifies things all that much. If anything, it creates a false sense of security - first developers get used to the fact that they can just assign to variables without synchronization, and then they forget that they still need to synchronize when they need to assign to more than one atomically.
If this were true, all of the explicit locking mechanisms in Python's threading module would be pointless. But in fact the GIL's "mutex" is quite a bit more limited than you are saying. It does not prevent all concurrent code from running. It only prevents Python bytecode from running concurrently in more than one thread. But the GIL allows switching between threads in between individual bytecodes, and "one Python bytecode" does not correspond to "one Python statement that performs an operation that you want to be atomic"; plenty of Python expressions and statements are implemented by multiple bytecodes, so it is perfectly possible for multiple threads executing concurrently to modify the same data structures with such statements, creating race conditions if explicit locking mechanisms are not used to prevent it. That's why Python's standard library provides such explicit mechanisms.
Not true. You can have serialized access to the same data structure that still have data race.
But as long as each Python process doesn't keep its local copies for those shared data structures, like free lists, no explicit locking is required if GIL is presented.
How?
> as long as each Python process doesn't keep its local copies for those shared data structures, like free lists, no explicit locking is required if GIL is presented.
I have no idea what you're talking about. Different Python processes each have their own GIL, and they don't share data at all (except by explicit mechanisms like communicating through sockets or pipes). Different Python threads share the GIL for their interpreter process, and if each thread doesn't keep its own local copy of data, there is explicit locking required if you don't want data races.
Simplest scenario, the read-increment-write cycle with 2 threads. Even with a mutex, it is still possible to have data race, if the lock is on per operation level.
For the second part, yep, it is a mistake, not processes, but threads.
With GIL, the thread is given the permission to operate on certain interpreter-related data-structures, like reference counts, or free_list like in PyIntObject. What I mean the active thread is free to modify those data structures without fear of data races, and there is no explicit locking required, if it doesn't hold its own copies of those interpreter internal states.
But GIL can only guard the interpreter's own states, not any user program's states. And yes, explicit locking for operating on your own data is still required.
https://docs.python.org/3/c-api/init.html#thread-state-and-t...
What you're describing is not "serialized access with a data race"; it's "multi-thread access that you didn't explicitly control properly".
> For the second part, yep, it is a mistake, not processes, but threads.
Ok, that clarifies things.
> the active thread is free to modify those data structures without fear of data races, and there is no explicit locking required, if it doesn't hold its own copies of those interpreter internal states.
I'm not sure I see why a thread would want to hold copies of those interpreter internal states, since if it did the issue would not be modifying them properly but having the local copies get out of sync with the interpreter's copies, since other threads can also mutate the latter.
That's not quite what the GIL guarantees. It guarantees that data can't change out from under you in the middle of executing a bytecode. But many Python statements (and expressions) do not correspond to single bytecodes.
What you are describing is simply a JIT compiler. Maybe are you suggesting to rewrite PyPy (its C part) in Rust?
The user is describing the opposite of a JIT compiler: a gradual rewrite of Python apps in Rust to feed into an ahead-of-time, highly-optimizing compiler. A JIT compiler would do quick compiles of Python code while it's running. The performance, reliability, and security capabilities of JIT vs AOT vary considerably with context. For predictability and security, I avoid JIT's wherever possible in favor of AOT's.
It's possible to do without the GIL, but up to now, it's been a damn to way of doing that.
Guarantee or not, it constrains whether something is usable as a drop-in replacement interpreter, especially if people can't tell which programs will break, and doubly so if the breakage is a subtle data corruption race that doesn't show up in tests.
It is not a real Python implementation if not compatible with C extension, it is just embedded DSL that has Python flavor syntax.
Is there really no situation in which an alternative implementation that only supports "pure Python" would be useful?
This really depends on your definition of 'being useful'. Jython is useful in a sense, it is being used in many Big Data solutions as a way to embed Python as DSL/UDF, like Pig/Hive, etc.
However, if without support for C extensions, it is not really a Python implementation, in a sense, I can't run a python script I just gripped from internet using the so-called 'alternative' implementation. So if the point of being useful is to be a replacement, then sadly, the answer is no, it is an everything-or-nothing situation.
Rust + Python seems a natural combinaison to me, and being able to have one single dev env (and maybe in the end, one single deployment mechanism) to do both is a killer feature.
And actually, I think having Python written in Rust would provide some other very nice properties:
- limit the number of bug you can introduce in the implementation because of the rust safety nets;
- can still expose a C compatible ABI and hence be compatible with existing extensions;
- the rust toolchain being awesome, it may inspire people to make it easy to compile a python program. Right now I use nuikta, which is great, but has to convert to C then compile, which make it a complex toolchain.
Modern languages need proper multithreading support, static types and fast compile speeds. Use golang, use kotlin, use dart, use anything but python & javascript.
We already have a plan to bypass the GIL: multi interpreters.
Having an implementation in Rust may make future improvement to Python easier, so it's better to have something exactly similar first, then start to hack it.
CPython can do that too, but this isn't really multi-threading, and it only bypasses the GIL in a very trivial sense.
But yeah, keeping the GIL is probably the only reasonable way to go if you want compatibility with existing extensions.
Cpython could do it, but currently can't provide much since the api to do it is only accessible from c.
>>>>> a = [1,2,3]
>>>>> a[2:]
[3]
>>>>> a[1:]
[2, 3]
>>>>> fh = open('~/.ssh/id_rsa.pub', 'r')
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: RefCell { value: [PyObj instance] }', src/libcore/result.rs:999:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
What would be really cool if this could one day be like Nuitka- but in rust. Write in python, compile into Rust. Maybe even support inline Rust like cPython supports inline C.First time I am hearing this. Can you share an example?
There also is https://github.com/rochacbruno/rust-python-example which is something I want to look into.
As for an example, I'm using Snappy right now, so here you go: https://github.com/andrix/python-snappy/blob/master/snappy/s... & https://github.com/andrix/python-snappy/blob/master/snappy/s...
It still requires you to compile the C part- which is why sometimes you need GCC when you're doing a pip install.
Maybe GP got confused?
open(os.path.expanduser('~/.ssh/id_rsa.pub'), 'r') fn builtin_hex(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(number, Some(vm.ctx.int_type()))]);
let n = objint::get_value(number);
let s = if n.is_negative() {
format!("-0x{:x}", n.abs())
} else {
format!("0x{:x}", n)
};
Ok(vm.new_str(s))
}
There's a big dispatch table, generated at compile time, and an interpreter loop. Just like you'd expect. It's useful if you happen to need a Python implementation to embed in something and want something cleaner than CPython. Probably slower, though.https://www.quantamagazine.org/how-space-and-time-could-be-a...
Let's put it this way: a million galaxies could blow up entirely to bits, and as far as we are concerned it wouldn't even make any difference.
- You leverage higher level concepts. This makes it easier to debug, easier to read, easier to maintaing, and all in all more productive.
- You get a vastly better toolchain. So of course again more productivity, but also potentially the possibility to include external dependancies or splitting the project in several parts. You can do that in C, but it's hell of a lot more work. Cargo in rust has a stellar reputation.
- Instead of providing Python, you can just provide cargo. Suddendly, your dev plateform is Rust AND Python. Together. With C it's very hard to do, but with cargo, it's possible to abstract all that and make them work like a singular entity. The possibilities are amazing.
- You prepare for the future. C is a legacy language. We use it because we don't have anything better now, tons of existing code and documentation, plus experienced devs. But 20 years from now, you will wish Python is not written in C.
- Free webassembly: being able to emit webassembly out of the box is going to get more and more important, as everybody wants it to become the lingua franca. Rust offers this for free. But even as importantly, it may help us to use webassembly dependancies into our Python project.
Since this has been posted to HN, the repo got 8 new PR.
Python with Rust as its foundation sounds like the best idea ever.
I’m curious to know whether or not it would be possible (or reasonable) to eventually get the same or better performance as CPython.
I think a RustPython implementation would be pretty cool. You could definitely take that opportunity to worry about performance more than CPython does while also worrying about interoperability more than PyPy does.
Or I'm missing your point and you're suggesting a drop-in replacement for CPython that supports all the same C-based libraries as CPython does.
No, that was my point basically, although I could imagine something like this shipping with some basic libraries and package support, and then having a similar ecosystem to the current python ecosystem.
I think not having support for C modules would hamper long term adoption. I would absolutely love to adopt this for my stuff, but off the top of my head- I use uvloop and confluent-Kafka, both of which are largely written in in C. Moving away from those would be hard-ish.
Literally all of them, without any issues? I'm working on implementing support for Ruby's C extensions in an alternative implementation and it's a right slog.
I have a Django app that does some heavy data serialization and I'm not yet ready to optimize those serializers in another language.
I can't wait to try this out.
Crumb. I didn't realise pypy is on 3.5.3. Loves me my f strings.
The data structures are slow by design.
The way we use these data structures is quite inefficient.
Having a fast interpreter only about doubles the execution speed in most programs leaving another factor of 50 open for future generations.
Ints and classes can be slow though.
Anything I don't know ?
Of course if you compare to static languages it's slow. Of course you can write low level specialized DS. Duh.
Or two and a half decades of performance neglect.
I've read about things like dicts, sort and the like getting faster implementations, but I've never seen a big effort to make CPython faster in general. In fact the first versions of 3.x were even allowed to regress to slower than 2.x.
> [Performance] isn't [...] one of the selling points of Rust
or
> this [...] software has been implemented poorly
It sounds like you're maligning Rust (isn't keeping promises) or RustPython (is implemented poorly), and it's easy to read "implemented poorly" as an attack on the implementers.
I really don't know how slow it is, I've not done benchmarks, but given that Rust is supposed to be efficient, it certainly can't be that slow, unless the implementation is really poor, I guess. I'm not saying it is because I don't know. If anyone has done benchmarks, please do share!
The reason for why I got the idea that it is slow, is that I believed the parent[1], and people have repeatedly claimed that CPython is slow.
[1] "to eventually get the same or better performance as CPython."
I assume this means that it is slower than CPython, and CPython is already extremely slow according to some people even on this page.
Sorry for the confusion. :)
One thing to consider is that CPython isn't slow because of the language it's written in, but because of optimizations it isn't doing (namely JIT, I think). Rust can't do the same things any faster than C can, and an early implementation of Python in Rust isn't likely to be much faster than an early implementation in C. Rust has the potential to make certain classes of optimization easier, eventually.
Assuming that was actively pursued. But if it was, all those other projects (Unladden Swallow, Dropbox's Python project, PyPy, etc, whose intend was exactly to make Python faster, wouldn't have been started).
It's not remarkably slow as long as you compare apples to apples, that is non-jitted vm-interpreters.
Jits pay a steep complexity- (and hence maintenance) price for their performance that should be taken into account when comparing.
Designing a significantly faster interpreter with comparable features is non-trivial from my experience [0].
Rust makes it easier to write programs that don't leak memory and don't have data races, but it doesn't make them run faster.
Rust also allows you to make architectural decisions in the name of performance that would be completely unmaintainable in C. See: the Servo project.
https://github.com/rust-lang/rust/issues/54878
This is not the first time it has been disabled due to an LLVM bug.
C vs. Rust: 6 wins for C, one draw, 3 wins for Rust
C++ vs. Rust: 5 wins for C++, two draws, 3 wins for Rust
The wins one way or another are also not by particularly large margins.
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
This may go on to shift marginally in Rust's favor once a soundness bug related to non-aliasing of references is fixed in LLVM and the compiler can safely leverage some guarantees that Rust provides that C and C++ cannot.
Also others have noted that speed was not a primary focus of CPython
Why do you think it's the "best idea ever"? What are the benefits over any other Python implementation?
Full security for Python apps would require consideration of each layer of abstraction:
1. User's code in Python.
2. The interpreter and extensions.
3. How these interact.
4. If added for performance or security, any assembly code plus its interactions.
Rewriting Python interpreter in Rust mainly addresses No 2. An example of a method to address all of them would be Abstract, State Machines which can represent simultaneously language semantics, software, and hardware. Tools like Asmeta exist to make them like programming languages. The verification would probably be manual, specialist work. Whereas, Rust's compiler gives you key properties with just annotations for many and working with borrow-checker for a few.
Has this actually been a problem, though? I'm no lover of python, but tons of people seem to use, for example, Django, without incident.
Rust will allow to safely invite a broader range of contributors, because there are so many things you don't need to check. This also means a smaller number of required tests, and because Rust uses higher level constructs that C, more productivity in general.
So basically, on the long run, more people, able to do more things.
Besides, on of the goals of the main implementation is to stay simple, which is hard to do in C. For those reasons, and because of the potential for unreliability and security, CPython is quite slow.
We can't optimize it, because it would make it too complex.
But with a rust implementation, one can hope to suddenly be able to apply more optimizations.
It's all theorical of course, but it's a nice hope.
I like Tcl the language a lot, and I love the idea of two language systems
One high level for scripting Tcl One low level for high performance commands and parts Rust
You can of course do that today, using Tcl and C But .. well C is no Rust
Having one team create complex tool using Rust, or Ocaml or Go or C++
And another team more domain oriented, created UIs and Interfaces and Script using Tcl (a language that is simple enough , yet powerful enough)
The one size fit all language, dont exist, I think, a two language team, is very good option
A (stretched) example, is SQL ..and the DBMS Expert programmers enrich the DBMS using C++ or whatever And domain experts use SQL and Procedureal-SQL to solve business problems
Tcl as a universal declarative language, is an idea I like
Lisp?
(or perhaps lisp is an n language system)
i dont know of any language, that have both, and was successful
Not sure if clojure specs, achieve the same outcome of optional typing, so maybe you have a point :)
The problem with that is that all the languages seem either to inherently be dynamic or static. Any attempt to add the other kind is hamstrung by the language's inherent tendencies, and it doesn't really work. Perl or python, for instance, have optional typing, but it's not checked at compile-time. And then there's things like c++ or d variant that--again, they don't quite feel quite as dynamic as they would in a dynamic language. I don't think these features can truly coexist well in the same language.
> both compile and interpreted
That's no hard ask. You just have to fight inertia, but there's really not much standing in the way of something like that.
Python optional typing is checked in an optional pre-compilation step. Except that there is no opportunity to use typing for optimization, this isn't meaningfully different, when used, from being checked as part of compilation. In fact, other than using type information for optimization it's pretty much what most compile time type checking does; compilation isn't an indivisible atomic step.
That's because they weren't capable of appreciating a language outside of fads and posts to social media.
It was a memorable experience, which I still fondly remember.
However it was also what made me not invest in languages without JIT/AOT thereafter, having to always dive into C all the time.
The relation of Tcl/C code changed quite heavily during the growth of the company, until we eventually rebooted our stack on top of the newly released .NET.
Something that we keep seeing on those "X rewritten in Y" over here.
Given the language names involved (Rust & Python), I’d like to suggest “Copperhead” as a name for it.
I think a rewrite in rust is more future proof: we benefit from a safer, more modern language to implement it, which comes with cargo, and hence, the potential of an hybrid python/rust toolchain and dev plateform.
If you'll permit the immodesty, another Rust parser is lrpar (https://crates.io/crates/lrpar) which is a more direct drop-in replacement for Yacc, but with better error recovery. [Note: I'm biased because I wrote parts of lrpar and the wider framework, grmtools, it's a part of.]
* using Rust's borrow-checking to develop new lightweight/shared-memory multiprocessing tools for Python (think "import SharedMemoryPool from multiprocessing") without having to mess with the GIL, so as to maintain compatibility with existing libraries;
* using Rust's type inference on Python code for applications in which type safety is highly desirable; and
* compiling Python code for speed, targeting all architectures and platforms supported by Rust (e.g., WebAssembly).
> Anything that can be Written in Rust, will Eventually be Written in Rust
Please go on, cite me, consider it «Attribution, Share-alike»
Atwood's Law was a prediction about the future that was based on something that had already happened (zillions of apps and libraries rewritten in JS). I'll quote your law when we have anything like comparable evidence that this is happening with Rust.
edit - it looks like it supports dictionaries with string keys, but not with integer keys.
They are able to deliver a demo in the browser for something that would normally require downloading and compiling. I think that’s pretty cool to show for a project people wouldn’t normally be able to try out with such low barrier of entry.
(There are advantages to running the same language on the server and client, and there's plenty of server-side web application Python code out there.)
I see this said quite often. What are they?
In more sophisticated systems, people sometimes like the client to "optimistically" do the same processing as it expects the server to do, so it can update its display more quickly.
Or if you have a mostly client-side application which builds up some fancy widget tree, sometimes people like to have the server do the same rendering as the client would so that it's there on initial page load, or so that search engines can see it.
But it might not give you the sort of compatibility between the client and server code that you're looking for.
Personally I'm more excited about other uses of Rust, but I can see why people are excited about Rust and WASM.
C++ isn't accessible but rust is? Only because they can't be bothered to learn: It complicated but its really not that hard.
Plug: D can happily compile to wasm
C++ isn't accessible to web developers compared to Rust. It's not just that I can't be bothered to learn, it's that I'm scared of all the security vunerabilities and memory corruption bugs I will write while I'm learning. And wjy put in that effort when I can learn Rust more easily, and get the ongoing benefits of my code being safe and reliable.
True, D also competes here. I should probably have put D on the list. Although my understanding is that a large part of the D ecosystem still relies on GC.
This is still not conclusive, as the runtimes will probably have to be significantly modified (at the ABI/System level, so around the edges) given that they will have to get memory from the browser etc. This leaves much room for WASM specific optimisation, especially given that the actual (let's say) garbage collector implementation is probably quite small compared to the code used to interface to it.
Writing C++ defensively (i.e. Do what the guidelines tell you, Preach Andrei and Bjarne etc), and using sanitizers cleans up a huge amount of C++ code.
Well sure, but the joy of Rust is that I don't have to worry about any of that. I can write my code naively, and the compiler will throw an error if I do anything stupid.
> This is still not conclusive, as the runtimes will probably have to be significantly modified (at the ABI/System level, so around the edges) given that they will have to get memory from the browser etc. This leaves much room for WASM specific optimisation
Certainly if/when this happens, other languages will be a lot viable in the compile-to-wasm. But you can run Rust (and C/C++) in the WASM runtime without issues today. And Rust even has a number of high-level libraries which provide binding to JavaScript APIs (e.g. https://github.com/rustwasm/wasm-bindgen)
I wonder how Rust is more “accessible” to JS developers than C or even C++. If you find C too hard to comprehend, you’re definitely not ready for Rust...
Rust code is actually pretty similar to JavaScript code, in that I can pull in a library `cargo add regex`, and work with high level abstraction right away.
Of course, there are new concepts to learn, but the Rust book covers these pretty well (I've been unable to find similar documentation for C/C++ that doesn't run to hundreds of pages).
My observation is that many people learn C/C++ at university (where there is lot's of support for learning the arcane folk knowledge of "the right way" of doing things in those langauges), and subsequently find Rust hard, because it introduces new concepts, and doesn't work in the same vein as C/C++.
For those of us coming from higher level languages, Rust is much easier, because it provides guard rails and prompts us when we go wrong, and because once a few new concepts have been learnt, a lot of our existing concepts can still be applied.