218 points · by zbentley · 5y ago · 203 comments
Then that leads to frustration and wondering why you even got rid of the GC in the first place if you end up with a crappier non-transparent reference-counted garbage collection with all these Arc/Rc. Some devs even seem to think that non-GC devs are silly poseurs who refuse to have a garbage collector only to reimplement it manually with reference counting. We are silly poseurs alright, but we're more efficient than that!
I share the author's conclusions: don't do that. If you find yourself slapping Mutexes and Arc/Rc all over the place it probably means that there's something messed up with the way you modeled data ownership within your program.
> If you find yourself slapping Mutexes and Arc/Rc all over the place it probably means that there's something messed up with the way you modeled data ownership within your program.
It only means that the data model doesn't agree with Rust's rules for modeling data (which exist to ensure memory safety in the absence of a GC). This doesn't mean that the programs the user wants to express are invalid. And this really matters because very often it doesn't make economic sense to appease the borrow checker--there are a lot of code paths for which the overhead of a GC is just fine but lots of time spent battling the borrow checker is not fine, and I think Rust could use a better story for "gracefully degrading" here. I say this as a Rust enthusiast.
EDIT: I can also appreciate that Rust is waiting some years to figure out far it can get on its ownership system alone as opposed to building some poorly-conceived escape hatch that people slap on everything.
Yes, and I think it's good to push back on that. I personally feel it's pretty misguided. I've been meaning to write about this, but haven't... so I'll just leave a comment, heh. Someday...
A related comment I wrote a while back about this: https://news.ycombinator.com/item?id=24992747
However, that example commits the Rust "sin" I always see with "spawn" explanations in that it packs everything into a closure.
Please, please, please ... for the sake of newbies everywhere ... please define a function and call that function from inside the spawn closure. This is one of the Rust things I spend the most time explaining and unpacking for junior engineers.
The separate function makes explicit the variables that are moving/borrowing/cloning around, which names are external/passed/closure-specific, and how it all ties together. It breaks apart the machinery that gets all conflated with the closure. They can always make it succinct again later once they understand the machinery more completely.
This gets particularly bad with "event loops" (I have a loooooong rant I need to write up about event loops and why they are evil--and it's not Rust specific) and deep "builder chains" (which I consider a Rust misfeature that desperately needs to go away).
On the other hand "just use Arc" is definitely smelly advice. I think going down that route, a new Rust programmer is likely to try to do something that really won't ever compile, and wind up really frustrated. Maybe we can distinguish this often-really-bad advice from the other mostly-ok-at-first advice?
But "scoped_threadpool" uses "unsafe".[1] They could not actually do this in Rust. They had to cheat. The language has difficulty expressing that items in an array can be accessed in parallel. You can't write that loop in Rust itself without getting the error "error[E0499]: cannot borrow `v` as mutable more than once at a time".
And, sure enough, the "unsafe" code once had a hole in it.[2] It's supposedly fixed.
If you look at the example with "excessive boilerplate" closely, you can see that it doesn't achieve concurrency at all. It locks the entire array to work on one element of the array, so all but one of the threads are blocked at any time. To illustrate that, I put in a "sleep" and some print statements.[3]
You could put a lock on each array element. That would be a legitimate solution that did not require unsafe code.
To do this right you need automatic aliasing analysis, which is hard but not impossible. (Been there, done that.) Or a special case for "for foo in bar", which needs to be sure that all elements of "bar" are disjoint".
[1] https://github.com/reem/rust-scoped-pool/blob/master/src/lib...
[2] https://www.reddit.com/r/rust/comments/3hyv3i/safe_stable_an...
[3] https://play.rust-lang.org/?version=stable&mode=debug&editio...
This doesn’t seem correct at all?
GC merely solves freeing memory when it is no longer needed. But it does not solve parallel access.
One of the beauties of Rust is that you can write highly parallel code and if it compiles it works. Meanwhile Python languishes behind the GIL. GC does not even attempt to solve multithreaded memory access.
I’m happy to be corrected if I’m wrong or missing something here.
For example:
fn foo<'a>() -> &'a [u8] {
let v = vec![0, 1, 2];
// returns a value referencing data owned by the current function
v.as_slice()
}
vs Go's: func foo() []uint8 {
// subject to escape analysis, but code like this would likely return
// a fat pointer into the heap--no complaints because there's a GC.
return []uint8{0, 1, 2}
}
> One of the beauties of Rust is that you can write highly parallel code and if it compiles it works. Meanwhile Python languishes behind the GIL. GC does not even attempt to solve multithreaded memory access.Python's GIL is unrelated to GC, but yes, Rust's borrow checker guarantees correct parallel access of memory. But I think this benefit is overblown for a couple reasons:
1. contrary to popular opinion, if you've learned how to write parallel programs, it's not tremendously difficult to write them correctly without a borrow checker. In my experience, whatever time I've saved debugging pernicious data races is lost by the upfront cost of pacifying the borrow checker. Maybe this wouldn't hold for people who aren't experienced with writing parallel code (but I imagine such people would have a harder time grokking the borrow checker as well).
2. most data races in my experience aren't single threads on a host accessing a piece of shared memory, but rather many threads on many hosts accessing some network resource (e.g., an S3 object). The borrow checker doesn't help here at all, but you still have to "pay the borrow checker tax".
Again, this isn't a tirade against the borrow checker, but an insistence that tradeoffs exist and it's not just a "you're just doing it wrong" sort of thing.
I'd add: some GC'd languages solve this with sending around deeply immutable objects (functional languages mostly), in a way that can be more flexible than the way Rust handles immutable objects.
I hypothesize that this mostly comes from a laziness in response as it's an easy response to give to people who are used to having a garbage collector. I come from the C world (still learning Rust) and every time I see one of these pieces of advice given I'm forced to facepalm.
Some people just try to force their way into a new language and don't realize that if you keep doing something that looks stupid or weird it probably is (and no, yours is not a special case)
I think the use case is "I haven't yet completely grokked the borrow checker and/or I don't have time to pacify it, but I would prefer not to copy potentially large data structures all over with Clone".
> Some people just try to force their way into a new language and don't realize that if you keep doing something that looks stupid or weird it probably is (and no, yours is not a special case)
You're responding to my comment which is about the Rust community prescribing this as a solution to newcomers. We're not talking about newcomers obstinately refusing to learn new idioms in the language they allegedly want to learn (although no doubt this happens, especially if the language in question is Go :p ).
To me it's not about performance. A little bit of time spent now appeasing the borrow checker will pay off ten fold later when you don't have to deal with exploding memory usage and GC stalls in production.
GC is great for quick hack jobs, scripts, or niches like machine learning, but I believe at this point it's a failed experiment for anything else.
I'm confused by the "it's not about performance. [reasons why it is, in fact, about performance]" phrasing, but in general a lot of applications aren't bottlenecked by memory and a GC works just fine. Even when that's not entirely the case, they often only have one or two critical paths that are bottlenecked on memory, and those paths can be optimized to reduce allocations.
> GC is great for quick hack jobs, scripts, or niches like machine learning, but I believe at this point it's a failed experiment for anything else.
That sounds kind of crazy considering how much of the world runs on GC (certainly much more than the other way around). I feel the need to reiterate that I'm not a GC purist by any means--I've done a fair amount of C and C++ including some embedded real time. But the idea that GC is a failed experiment is utterly unsupported.
tl;dr: there are significant GC performance problems that a borrow-checker doesn’t solve. I can imagine cases where the performance improvement is significantly less than you might hope.
In my opinion, Rust is optimized to be a systems programming language. As such, we'd expect that it shouldn't really be your first choice for writing an "application". (I'm not referring to the OP at all here)
HOWEVER, Rust is such an excellent language that we all want to use it to write applications ANYWAY. That's kind of amazing in and of itself- that people want to deal with a non-GC'd language at all to write applications. Because, really, garbage collection is awesome and there's almost zero reason to avoid it unless you need extremely predictable performance, or very low runtime overhead, etc.
As far as wrapping everything in Arcs and Mutexes is concerned: Yes, that's ugly and it's a lot of extra typing. On the other hand, your performance is still likely to be orders of magnitude faster than Python for some general application-type tasks, and it will likely avoid headaches with the borrow checker, etc.
So, honestly, I don't know if I recommend doing that or not. Want I want is to be able to tell people to not use Rust for what they're doing. I'd like to have a different recommendation for a "garbage collected Rust" but there really isn't anything that I think is good enough for the title. Maybe Scala 3 (I haven't played with it yet) or OCaml when its multi-core stuff is done. Maybe F# or C# are good enough, too.
Is this really the reason, or is it because people think they will get free performance wins by choosing the correct language? The plethora of articles detailing a developer's story trying to write X-style language in Rust shows that most are not approaching Rust with the correct mindset.
I have limited experience is Rust, but seems like most people are attracted by shiny new toys in the language. Many people have issues with OO languages, and the separation of data and function is attractive. But it lacks the run time most application developers have come to know, specifically GC and easy references.
I'd say there are three things that most people rave about with Rust:
* traits as type classes (even if they don't know the term "type class") * enums and pattern matching (not even as flexible as some other languages like MLs, but way more than is possible in most popular languages with only Swift coming close) * the Iterator trait. I might write a sonnet about how much I love Iterator in Rust. It's lazy iteration, but it's also optimized at compile time to basically just be turned into a for loop.
I hope at some point we'll have this "garbage collected Rust", but for now OCaml, Scala and F# all have a worse developer experience than Rust. I could add Haskell to that too.
I've been thinking for some time that something like Go but based on a ML would fill this "garbage collected Rust" niche quite well. Maybe something built over Rust itself to leverage all the ecosystem? You could write all of the glue code in this language, have access to a large ecosystem of libraries and have an option for high performance code. This would also complement Rust nicely: I know that OCaml has a really fast compiler, which would be a breath of fresh air for the community.
F# on Visual Studio + .NET ecosystem (which includes C++/CLI, C# and first class support for COM/UWP) is worse than Rust?!?
I do agree that language built on top of the Rust ecosystem (kind of like how PHP exposes a lot of C libraries) could make a lot of sense.
D and Nim are both good candidates IMO.
I have exactly the same problem. Rust is nearly perfect to me, due to its non-nullable type, traits, package manager. It's just that losing garbage collection is not justifiable in my use cases. I've researched several languages but nothing "clicks" unlike what Rust did to me several years ago. C# might be my best bet but it lacks statically compiled binary. Go is my next bet but it lacks a sophisticated typesystem. Kotlin is my third bet but the Java toolchains are slow and too "enterprise-y". Swift is too Apple-centric and has weird corner cases like you can't change the order of the keyword parameters, due to its Objective-C origin. Life is full of trade-offs, I guess!
Mutexes aren't an entirely foreign concept to many programmers. Obviously if someone can architect their system in a way that doesn't require Arc<Mutex<_>> then go for it, but we need to be careful about giving blanket advice without alternatives.
Create a one-buffered channel: `make(chan T, 1)`. To acquire, receive from the channel. If the object is in use, the receive will block (goroutine put to sleep) until it’s available. To release, send the acquired object to the channel.
On a language level, no mutexes.
Folks really ought to read the C/C++ literature to understand why Rust evolved in a unique direction. That gives better compare/contrast.
Also, a lot of Python idioms are actually from C++ (e.g. mixins, iterators, operator overloads, etc).
Anyway, to reiterate: folks interested in systems languages should read the C/C++ literature and actually become a systems engineer first.
Sounds like a good idea for the post-singularity age of infinite lifespans, but what folks really need to do is learn what they need to learn as best they can when they need it.
Unfortunately the C/C++ literature is dense and not at all approachable. The Rust literature is much, much better for newcomers to systems programming (partly because it doesn't have to cover a load of weird failure cases that simply don't exist in Rust).
> one _cannot_ just arbitrarily “go” from a higher level language to a systems language.
I mean, it's like learning anything new. You have to do a bit of unlearning, and grasp the core concepts. I don't think there is anything especially difficult about systems languages. I had a background of JavaScript and PHP, and I was able to pick up Rust well enough to use it in my day job in a couple of weeks.
Many developers these days scarcely read books on subject matter. But if they did read books, they would find there’s actually more C/C++ literature and established best practices than there is for Rust (naturally).
The effective C++ series comes to mind as something not just approachable, but enjoyable and largely insightful.
The truth is... systems engineering is a discipline which requires an understanding of historical context. You get that with the C/C++ books! I highly recommend reading on it to better appreciate Rust.
Learning the idioms and conforming to a new language are hard, especially at the beginning, and people are lazy.
In particular, Python's import, exception handling, and object systems are based on Modula-3's (though IIRC it did also borrow some C++ innovations for the object system).
(Modula-3 is the Velvet Underground of programming languages: your average programmer/listener has never heard of it, but it influenced so many languages/musicians you have heard of)
This is an extremely weird take. So before I can code some rust I should first get a new career and master C/C++? Talk about barriers of entry and gatekeeping. I think I may have toyed around a bit with rust - because its fun, and as I am not a systems engineer (just an other type of engineer) I am deeply sorry.
On the subject of python, I think Rust has a very powerful niche it could take: slightly modifying an old Google philosophy(which they can't stick to anymore for a million and one reasons of course): "Python where we can, Rust where we must". To my mind it could be a very pleasant recipe for a large number of startups.
However data structures in Rust are not at all straightforward. Especially implementing traits, such as an Iterator for a Hashmap. And std implementations use loads of unsafe so beginner me became increasingly confused as to whether these things were not expressible in safe rust.
Many people don't realize that actually referencing all the things all the time is LESS efficient than copying stuff around on modern architectures, unless you copy really big things. This is because the majority of improvement of memory access in the recent years is seen in sequential speeds but not latency.
That's just not a very useful statement to a beginner. Rc/RefCell and Arc/Mutex have their use, for data with patterns of lifetime or mutability that cannot be derived at compile time based on program syntax - something that comes up all the time in practical programs. Of course one should seek to refactor these things out whenever possible (among other things, programs that use shared data heavily are also harder to survey wrt. correctness), but to say as a generalized statement that there's no case for this feature is just not correct. The feature is also intentionally heavy on syntax so there's no missing where you're using it.
I would love to see more writing on this.
Python doesn’t expect you to share references to things - it’s just that the API that was being copied follows an imperative style that mutates objects.
In the Python world if this bothers you you're supposed to use the adapter pattern to Pythonify the mechanically ported API.
For instance - lets look at sequential operations against a DB versus batches. In a sequential style, you might iterate your items and just write them one by one. Alternatively, in a batched style you might need to do things like prepare queries or store your queries alongside the actual data values, then hand it all to a batch mechanism that will perform the write. The ergonomics are completely different but at the end of the day the result (rows in the table) will be the same. So even in the same language you will see totally different ways to go about solving the same problem. This is why I do not really see this as a python/rust argument and more of a generic program architecture argument.
In the above db case - the programmer isn't disappointed that they need to rewrite their iterative loop approach because the know that the batching approach is going to be much faster and will achieve their goals.
I think the same parallel can be drawn here: it is not a bad thing to have a slightly different API. Especially in the context of going from a dynamic language to one that is compiled and more performant.
All of this is kind of a moot point though because the Rust lib in question doesn't have any instructions/documentation or design docs so it is hard to say for certain what the intention is here other than a port for the sake of porting.
What's additionally challenging in this case is that the design of the underlying rust API (the norad crate[1]) was also more or less done, so this really was just a matter of trying to shim.
In any case, I think we more or less agree; just trying to provide a bit more background on the motivation. This was originally just circulated as a gist between a few interested parties, who were largely familiar with the motivations; it certainly didn't occur to me that it might be interesting to a general audience.
I wouldn't say it's "predominant". Some instances are code authors trying to bring their library to new audiences (c/c++ frameworks with multiple language bindings), or developers unfamiliar with the language but want that specific API in their own (Python's requests library is a great example, cloned in many languages now).
font = Font.open("MyFont.ufo")
glyphA = font.layers.defaultLayer["A"]
point = glyphA.contours[0].points[0]
point.x = 404;
assert point.x == glyphA.contours[0].points[0].x
The author apparently wants to be able to perform ad hoc modifications to an existing font.Unfortunately, it's not clear from the article what the use case is. Most of the time I've worked with fonts, they're treated as immutable values.
If the idea is that a font needs to be built from a serialization format, then an alternative approach would be to eliminate the python mutable interface and replace it with a build function that calls the underlying Rust to build a Font. That way Python never needs to deal with mutating a font.
Rust lets you take unlimited numbers of references to an immutable value. That's not a problem, other than defining lifetimes if you pass those references around and/or hold them in structs.
The problem arises the instant you want to mutate the value behind a reference. Hold just one active immutable reference at the same time, and that won't be possible. Note that mutable and immutable references can in some situations exist in the same block thanks to non-lexical lifetimes.
This approach assumes of course that there are no reference cycles in the graph. If there are, you’ll need some way to clean them up if Weak isn’t sufficient.
Alternatively, is there a way to ask Python to allocate memory for you, which is then subject to Python’s GC? If so, you could make a smart pointer type for this and use that everywhere. Though you’ll still need to figure out how thread safety works. So this really would only be for handling reference cycles.
Honestly, as someone who has written way more Python than Rust, this seems like bad API design regardless of language. This screams "it's impossible to take a font, make two separate modifications to it, and then work with those separate modifications at the same time", because deepcopying objects is usually very difficult.
My experience is the exact opposite. Pervasive shared mutability leads to developers making lots of unnecessary copies out of fear that some other part of the code will change values out from under them.
Even in Rust, the `Clone` trait produces a deep copy.
Copying only up to a specific depth in a general way is what is difficult.
I would argue that shallow copies, id est the depth being 1, are far more difficult to realize that copies of unbounded depth until a value o trait `Copy` is reached, id est a type that is purely encoded by the data it takes up on the stack and owns no further data and can thus be fully be `Clone`ed by copying it's stack bits.
Clone is not really a deep copy. I like the description that says it is "deep enough to give you an object of identical/independent ownership (of what you started with), but no deeper".
Example: Rc<String> when cloned only gives you another handle to the Rc, the string data is not duplicated (for this reason we don't call it a real deep copy). You get a new rc handle that is on equal footing with the old handle.
There is plenty of Rust types that consist of tree-shaped ownership relations with no frills - in these cases clone and deep copy are identical. Let's say for example a HashMap<i32, String>.
The principles are still quite similar and it still seems easier to implement to me than shallow copies as a generic trait.
I don't know how I would fit shallow copies into Rust's trait system.
Maybe https://www.youtube.com/watch?v=T-TwcmT6Rcw (Dataclasses! We could cheekily say Python gets better at something Rust does - dataclasses makes Python better at records.)
And https://www.youtube.com/watch?v=S_ipdVNSFlo
This talk (2013): https://www.youtube.com/watch?v=OSGv2VnC0go Unfortunately this video is now a bit out of touch with modern Python.
Another (2013) classic: https://www.youtube.com/watch?v=HTLu2DFOdTg it is very well known, and it has the very memorable advice: what's a class that only has one method? That should be a function!
Beyond PEP 8 -- Best practices for beautiful intelligible code - PyCon 2015
It's not clear if you mean python got better at storing records than previous python or if it got better at storing records than rust.
To be clear, dataclasses make python better at storing records than what was previously available in python but still not as good as Rust (serde, immutable defaults, no perf penalty with immutability).
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!(I also divide Python into two big camps: building software/apps vs. data science and analysis, which further subdivides the community - if you ever read a post on how to do XYZ from the perspective of a data hacker it will usually fall into the non-pythonic category)
There is a fantastic book in the Ruby world called “Eloquent Ruby” but I have yet to encounter an analog for Python.
RealPython has some cool posts, though. I think they’re doing the best job pushing more modern/clean practices forward at the moment.
Nim/Nim-lang makes it much easier to write Pythonic code. Minus all the complex things that only smart(er) programmers get(like GC, etc.), with Nim you can write code that is much more readable.
Another win for it is that it has very limited support for OOP, which IMHO sucks in terms of readability and understanding what the code is doing(as compared to imperative code).
[0]: https://doc.rust-lang.org/reference/expressions/operator-exp...
https://doc.rust-lang.org/std/convert/trait.TryFrom.html#exa...
If absolutely necessary, Objects can be downcast by using Any (though I've personally not needed to write Rust code that needs this): https://doc.rust-lang.org/std/any/trait.Any.html. Edit, instead I tend to rely on Rust enums (for it's algebraic type features).
Also, in some cases you may end up wanting to implement Deref or DerefMut, https://doc.rust-lang.org/std/ops/trait.Deref.html, but this shouldn't be use to create inheritance, it's more used for getting references from one type to another similar type (like String derefs to &str for example).
> This was my initial approach, but it started to become pretty verbose, pretty quickly. In hindsight it may have ultimately been simpler than where I did end up, but, well, that’s hindsight.
Also experimental support for pyo3 extensions. But really the main idea of the project is static python and complete recompilation (not interoperability with dynamic python code).
Personally, I find OO designs to be enhanced by this principle, so I don't think it's only something one does in Rust. I certainly learned it from Rust though.
Even if B is technically mutable (which 99% of the time it is because almost everything in Python is mutable), just don't mutate it and pretend like you're not allowed to do so.
This gets you pretty far, but it's hard to ensure that nobody else ever mutates B. If B is technically mutable, and there are multiple mutable references to B, then when you invoke some other object in the course of your work, control might come back to you with B mutated without you realizing it. This is why the XOR is so important: if B is shared (with you) and mutable (not by you), B could change under you while you've passed control temporarily to someone else.
This is certainly less problematic than having multiple mutable references, but it's still a source of complexity. As a very small toy example, consider iterating forward over an array while deleting elements.
Which you can get around with rawset, that's what it's there for, but it will catch any idiomatic attempt to mutate the data.