430 points · by rch · 7y ago · 194 comments
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?
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.
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:
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.
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.
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...
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
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.
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.
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.
Modern languages need proper multithreading support, static types and fast compile speeds. Use golang, use kotlin, use dart, use anything but python & javascript.
It's possible to do without the GIL, but up to now, it's been a damn to way of doing that.
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. open(os.path.expanduser('~/.ssh/id_rsa.pub'), 'r')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?
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.- 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.
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 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.
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 ?
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.
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 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.
Also others have noted that speed was not a primary focus of CPython
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).
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.
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
That's because they weren't capable of appreciating a language outside of fads and posts to social media.
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)
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.
* 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.
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.
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.
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.)
But it might not give you the sort of compatibility between the client and server code that you're looking for.
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.