Writing Pythonic Rust
cmyr.net
cmyr.net
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).
It is probably because of all my years with Ruby that this seems so off to me, but also, I hear you. Hmm.
The issue in Rust is that "spawn" is generally the first time that a programmer is forced to confront closures--before that they can completely ignore them.
It is a quirk of Rust that someone who "just wants to spawn a thread" suddenly gets all this language overhead dumped on them in a block.
> might be my bias coming from a more functional background before learning Rust
This is exactly the problem. The people I'm dealing with are coming from "imperative land" and haven't had a functional background. Someone stepping up to Rust as "C with memory safety" does not have any of that functional background.
Please do remember that a "closure" is built on a lot of prior abstractions. What is a "scope"? What is "variable capture"? What is "heap" and "stack"? Why does that matter here and not normally?
No programming language is only used by experts, and Rust is no exception.
The issue is that "spawn" smacks you with a bunch of that baggage all at once.
I don't understand how a function that is defined in-place is more clear than a nice function on its own. Perhaps because it gives a sense of continuity (like in async code), but man, it's really painful to read (at least to me). In fact, if I have to write some Rust right now, all my closures would be defined elsewhere, whenever possible.
A lot of embedded code NEVER calls malloc (thus the need for no_std in Rust). Consequently, you can go a long way in embedded without really knowing the difference between stack and heap.
"Embedded programmer" does not imply "Linux Kernel Hacker".
When I started with Rust, I actually thought that the common
spawn(|| …)
syntax was something special, not just a closure with no variables.
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?
Yes, I guess to me they're distinct, but I can totally see how it may seem similar. I'll try to make sure to make that explicit when I talk about this, thanks!
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...
Using unsafe isn't "cheating". The whole point of using Rust is that you can encapsulate very small amounts of "unsafe" code within a safe abstraction, and know that there is no way to abuse the safe APIs to produce undefined behavior. The formal verification project "RustBelt" [0] has proven exactly this -- safe Rust code composes arbitrarily to produce safe behavior.
There is still a burden of proof on anyone writing a safe function that uses unsafe functionality internally. Keep in mind that "unsafe" Rust still poses more restrictions on the programmer compared to raw C/C++.
> The language has difficulty expressing that items in an array can be accessed in parallel.
The Rust borrow semantics is based on `exclusive XOR shared` references. At the first order of approximation it's not possible to mutate a value through a shared reference. Interior mutability complicates this image somewhat, but it's enough to explain why what you wrote is wrong.
Spawning `n` threads and giving each thread a mutable reference to the vector `v` goes against the above borrow semantics because that would result in `n` exclusive references. Only through exclusive references is mutation allowed. Since this is not allowed it becomes a compile-time error.
In other words, it's not that the language has "difficulty expressing" that scenario. It was explicitly designed to not allow it.
[0]: http://plv.mpi-sws.org/rustbelt/"Within a safe abstraction" is the question. The question is whether a piece of encapsulated code is always memory-safe for all uses. There's no guarantee of that from the language. The RustBelt people are working on tools for that, but it will probably require proof work in Coq for each bit of code containing "unsafe" to get there.
Look at the scoped_threadpools example again [2]
use scoped_threadpool::Pool;
fn main() {
let mut pool = Pool::new(3);
let mut v = vec![1, 2, 3];
pool.scoped(|scope| {
for i in &mut v {
scope.execute(move ||{
*i += 1;
});
}
});
println!("v: {:?}", v);
}
There's an implicit assumption here that all the values returned from the iterator at for i in &mut v
are disjoint. But iterators, in general, do not guarantee disjoint outputs. An iterator which returned each reference value twice, for example, is a valid iterator. But used in the context above, two threads would receive mutable access to the same element of a vector. That seems to violate a core Rust safety assumption.This would be a nice test to run through the version of the Miri interpreter that implements the dynamic "stacked borrow" checks from the RustBelt group.[2] That tool should catch this.
[1] https://news.ycombinator.com/item?id=24992747
[2] https://plv.mpi-sws.org/rustbelt/stacked-borrows/paper.pdf
> for i in &mut v
> are disjoint. But iterators, in general, do not guarantee disjoint outputs. An iterator which returned each reference value twice, for example, is a valid iterator. But used in the context above, two threads would receive mutable access to the same element of a vector. That seems to violate a core Rust safety assumption.
Your assumptions here are wrong. "An iterator which returned each reference value twice" could only be implemented using unsafe Rust, and code emitting multiple co-occuring mutable references to the same value are instant-UB. In other words, a "safe abstraction" being able to do this is actually not a safe abstraction at all. This would be a bug in the implementation of the custom iterator.
In fact, if you tried to prove such an implementation using the formal tools (Iris) from RustBelt you wouldn't be able to do it. I know, because I've done it as part of my course work under Lars Birkedal.
I'm not sure if you misunderstanding how `&mut v` turns into an iterator, which values it spits out etc, or what is happening. Let's look at how that code is translated into a program and typechecked. First, let's look at the for-loop itself. Anything on the form of
for x in y
must have an implementation of the `IntoIterator` trait for the type of the expression `y`. Whatever that type might be. In this case `y` is actually `&mut v`, where `v`'s type is `Vec<i32>`. Luckily enough, an implementation of `IntoIterator` exists for any `&mut Vec<T>`. [0]Looking at the expanded signature we can see that the associated type `Item` is `&mut T`. This tells us that the types the resulting iterator will produce are `&mut i32`. Keep in mind that this reference is into the backing memory store of the `Vec<i32>` of `v`. This is where Rust's semantic help us.
You say the following:
> But iterators, in general, do not guarantee disjoint outputs.
The issue with that statement is that iterators don't have to. Rust guarantees that condition. Safe Rust can't return multiple mutable references to the same value. Further, any unsafe implementation, even when exposed through a safe interface, giving this behavior is a bug. It would be great if the compiler could statically verify unsafe code too, but if it could there wouldn't be a need to call it unsafe.
> The question is whether a piece of encapsulated code is always memory-safe for all uses. There's no guarantee of that from the language.
That is ultimately impossible to prove completely and statically. Turing and Gödel made sure of that. However, some things that the compiler can't prove we can still prove as outside observers. Often these things will boil down to controlling and checking the states of several variables before performing an unsafe operation, but knowing that in a given context the operation is safe.
The first part of the above quote is partially true. However, if we assume a given unsafe implementation is indeed safe then the rules of Rust's semantics make the composition of any number of safe APIs a completely safe composition. This is a strong, useful statement because it means the very few places where unsafe is required can be easily checked, and every other piece of code doesn't have to spend mental energy for the programmer to consider the safety of their implementation.
[0] https://doc.rust-lang.org/std/iter/trait.IntoIterator.html#impl-IntoIterator-19So how does Vec return mutable references to elements? Unsafe code, apparently. You can't write your own safe collection class with an iterator and return mutable references. You'd need a proof of disjointness system to do that.
The question is whether a piece of encapsulated code is always memory-safe for all uses. There's no guarantee of that from the language. That is ultimately impossible to prove completely and statically.
One can construct code for which memory safety is not decidable. That's a good reason to reject it. The Microsoft Static Driver Verifier has a simple solution - if symbolic execution can't verify safety within some time limit, it rejects the driver.
If you have a mutable binding to a vector `v` you can get a single mutable reference to one of the elements of that vector at a time. Because getting a single mutable reference to an element requires taking a mutable reference to the vector the disjointedness invariant is upheld. This is the core of the Rust borrow checker. If you're unsure about the semantics you should be reading about it, not trying to sus them out from a fairly surface level discussion on HackerNews.
This code:
for x in &mut v {
*x = // ...
}
is perfectly valid. For every iteration of the loop only a single mutable reference to an element exists, and the reference is dropped before the next mutable reference is taken. This following piece of code is a full example that showcases how taking two mutable references is not allowed. struct ComplexNonCopyClone {
a: u32,
}
fn main() {
let mut v = vec![
ComplexNonCopyClone { a: 1 },
ComplexNonCopyClone { a: 2 },
ComplexNonCopyClone { a: 3 },
];
let mut_one = v.get_mut(0).unwrap();
let mut_two = v.get_mut(0).unwrap();
mut_two.a = 4;
println!("{}", mut_one.a);
}
Do note that using `mut_one` after `mut_two` is important, as otherwise the compiler will infer that `mut_one` can be dropped before `mut_two` is create, removing the clash.> So how does Vec return mutable references to elements? Unsafe code, apparently.
The implementation can be found quite easily[0]. It's essentially invariants upheld by runtime checks and knowledge about the state of the given references/pointers. Notice the comments starting with "SAFETY". They explain the assumptions/conditions/reasons that make the code inside the `unsafe` block safe. If these assumptions can never be violated with malicious input or calling patterns then the code is actually safe and it can be a safe wrapper.
[0]: https://doc.rust-lang.org/src/core/slice/index.rs.html#149-190To recap: the interesting issue is the thread pool example which spins off a new thread with a mutable reference to each element of an array. That's a rather unusual thing to do. It is only safe if each iteration returns a reference disjoint from all other references. Because Rust at the language level does not understand disjointness within an array, it needs a hack using "unsafe" to make this work. The borrow checker would not allow this in safe code.
chunks_mut uses the same trick, with more unsafe code.
My point in all this is that because the language doesn't have syntax for talking about disjointness of parts of an array, each time this comes up, another hack in unsafe code is required. But enough here; I may say more on the Rust forums.
That isn't true at all. The implementation of scoped_threadpool being in rust is all the evidence you need that they did not cheat. unsafe is a perfectly valid construct in rust that does not subvert its benefits. It just is a reversal of the defaults in other languages (unsafe by default - opt-in to safer constructs like smart_ptr).
People freak out too much over this stuff. If you are learning - feel free to use escape hatches from "idiomatic rust" but recognize that you aren't being idiomatic (and therefore may be handicapping your learning!). Its okay to use unsafe despite idiomatic rust trying to avoid it unless necessary (and even then providing safe wrappers over it). Its also okay to use Arc<Mutex> and the like if you need to just recognize there may be a better way.
thread::spawn uses unsafe code. sleep uses unsafe code. Is your own example not in Rust? Are you cheating?
(And yes, the spawn version isn’t optimally concurrent. The comment was long enough without getting into that. People struggle to get examples to compile before they worry about things like this. That would be next steps.)
There are a relatively small number of trouble spots. They include, at least:
- No way to talk about partially initialized arrays in Rust, which leads to Vec needing "unsafe".
- Back references, which makes some kinds of trees, and of course doubly-linked lists, difficult.
Those I've mentioned before. From the discussion above, add:
- Problems around interior mutability within arrays, where you need some way to say, and prove, "a is disjoint from b", before working separately on a and b.
These are classic proof of correctness areas. It's fairly straightforward to state the conditions that have to be proven, and usually not that hard to prove them. The RustBelt crowd seems to be working on this.
Maybe they'll come up with a way to prove out conditions like that, short of grinding away by hand in Coq. Most of those problems are within reach of a fully automatic prover, like a SAT solver.
You're right, but current Rust cannot express logical preconditions in code, much less compiler-checkable proofs. Many groups are working on this via a variety of approaches, but it will take some time before there's a common standard for expressing these things as part of the Rust language itself.
I agree with Animats here, to work around typesystem issues means that the type system still isn't expressive enough to define certain proprieties in a safe way.
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.
Maybe I’m just a bad enough programmer I write parallel bugs. But C++ certainly doesn’t make it easy to write correct code in any way.
I personally think it’s pretty darn difficult to ensure correctness in a large program. Especially when multiple programmers are involved. And especially when you are adding features to an existing system.
However I will also admit that I haven’t written a large Rust program so I can’t claim to have run into all of its warts.
There’s no silver bullets in life. I work primarily in video games. GC is the bane of existence and is something that provides seriously negative value.
We definitely agree it’s all a trade off. GC provides some value and some costs. Borrow checkers provide some value and some cost.
> 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).
I think my initial response was that Rust’s model exist for more than just that single reason. Whether those reasons or trade offs are useful depend on the program in question.
In my work I never want a GC, but damn would I love a borrow checker.
The problem with ownership-based safety for massive parallelism is that the mechanics of agreeing on and determining ownership don’t scale and often can’t be determined at compile-time. Some other safety mechanics don’t have these limitations. C++ doesn’t have them built-in but you can implement them.
IMO the key to writing parallel code is to keep the parallelism confined to a small kernel rather than sprawling throughout your codebase. If you try to bolt on parallelism then you’re going to have a bad time. It needs to be part of your architecture. It’s not easy, but it’s easier than writing parallel code that will pass the borrow checker IMHO. But yes, we may have to agree to disagree.
> We definitely agree it’s all a trade off. GC provides some value and some costs. Borrow checkers provide some value and some cost.
Agreed!
> I work primarily in video games. GC is the bane of existence and is something that provides seriously negative value.
I’m very curious about videogames development. In particular, I get the impression that aversion to GC in videogames comes down largely to experiences with Java back when pauses could be 300ms. I’m very curious if Go’s sub-millisecond GC (and its ability to minimize allocations, etc) would be amenable to videogame development. Thoughts?
> I think my initial response was that Rust’s model exist for more than just that single reason. Whether those reasons or trade offs are useful depend on the program in question.
Heartily agree.
> In my work I never want a GC, but damn would I love a borrow checker.
In my line of work, I like the idea of using Rust but realistically the economic sweet spot is something like “Go with sum types” or “Rust-lite”.
It really just comes down to average/worst case time.
60Hz - 16ms 90Hz - 11ms 120Hz - 8ms 144Hz - 7ms 240Hz - 4ms
Modern games are expected to run anywhere from 60 to 240 frames per second. 60 is the new baseline. VR runs anywhere from 72 to 120. Gaming monitors regularly hit 144Hz. And esports goes as high as 240 and even 360.
In Unity C# GC can take tens of milliseconds. This is, uh, obviously very bad. High tier unity games spend a LOT of time avoiding all allocs. This is not fun in a GC language. Most indie games just hitch and its pretty obvious. I’m not sure if Unity’s incremental GC has graduated from experimental mode.
If a GC had a worst case time of less than a millisecond that’d be fine. That’s actually a pretty big chunk of a 7ms frame, but hey probably worth it. If it’s usually 250us but once a minute spikes to 3ms that’ll cause a frame to miss. If once every 5 minutes it’s a 50ms GC that’s a huge hitch. For a single player game it’s sloppy. For a competitive multiplayer game it’s catastrophic.
Unreal Engine actually has a custom garbage collector. But it’s only for certain days types and not all memory. That’s a nice compromise. Games in particular are good at knowing if the lifetime of an allocation is short, per frame, long-term, etc.
Well, Minecraft is written in Java, and it runs fine from what I’ve heard. In .NET land, there was a short lived toolkit for C# called XNA - Terraria is (was?) written in it. Both Java and C# are garbage collected.
I haven’t looked at Unity too deeply, but isn’t Unity (and the games made in it) built in C#?
I think C# is popular because it allows the above. When Java has proper value types it might be suitable for writing games.
To be clear, the problem isn’t pointer indirection, but rather lots of objects on the heap, right? Pointers should be fine as long as there aren’t many allocations (e.g., pointers into an arena)?
> I think C# is popular because it allows the above. When Java has proper value types it might be suitable for writing games.
Go also has value types, FWIW, and they are a lot more idiomatic than in C# from what I’ve observed.
AKA Ocaml.
That’s a dangerous misconception. The Rust ownership model only guarantees that the program is free of data races. That’s a necessary but not sufficient condition of program correctness.
Only for threads accessing in-memory data structures, it does nothing for other kinds of data access scenarios either to external resources or via OS IPC mechanisms.
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 ).
For basic stuff I agree, though I wouldn't use it.
> about the Rust community prescribing this as a solution to newcomers.
There's probably a sweet spot for using those constructs in not so obvious places while going through the simpler stuff in a more idiomatic way
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.
That's the story that GC sold us. History has proven it wrong. Citation: the fire hose of articles on HN about how GC bit people in the ass, and they now have to go back into their code and write a bunch of duct tape code to work around Garbage Collector Quirk #4018 de jure that results in hitching, insane memory usage, and random OOMs.
> That sounds kind of crazy considering how much of the world runs on GC
And much of HN runs on comments complaining about the _absurd_ amounts of memory all those non-bottlenecked applications use to do otherwise simple tasks. Or the monthly front page articles about developers and companies working to fix their otherwise straightforward, non performance critical production services that are choking themselves because the GC is going wild.
I say GC is a failed experiment because it promised that programmers would be able to write code without worrying about memory. But ever since its popularization 26 years ago with the dawn of Java, coders writing in garbage collected languages have been doing nothing but worrying about memory. The experiment failed. It's time to move on.
The borrow checker is an infantile incarnation of a bigger idea that is finally panning out. Rather than garbage collecting during run-time; garbage collect during compilation using static analysis. Being in its infancy it's not as easy and free to use as we'd like. But it's the path forward. And just like garbage collection before it, in the vast majority of cases, programmers don't care whether it's more or less performant. Garbage collection was vastly less performant than manual management. But it required _so_ much less developer time to build the same applications. My argument is that Rust's borrow checker, as painful as it is, results in more developer time up front, but less developer time overall when you consider the long tail of code upkeep that garbage collected applications demand.
Hence my comment: "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."
It's not about performance; it's about saving yourself the time of having to come back to your code a month later because your TODO app is using a gig of RAM and randomly hitching.
If your GC program is using excessive RAM, that’s because of a memory leak, not the garbage collector. This can happen in C/C++ as well; just malloc/new and forget to free/delete. Last I checked, C and C++ aren’t garbage collected languages.
Note also that GC languages don’t even have the circular references case to worry about since they don’t have any need for reference counting in general.
That’s my memory and battery capacity, not theirs.
I follow HN daily and very rarely do I see articles lamenting GC (I'm only familiar with a small handful of incidents including some pathological cases with Go's GC on enormous heaps (many terrabytes) and some complaints about Java's GC having too many knobs), certainly not in the general case. Indeed, for the most part people seem quite happy with GC languages, especially Go's sub-ms GC. In particular, memory usage (and thus OOMs) have nothing to do with GC--it's every bit as easy to use a lot of memory in a language that lacks GC altogether. This is incorrect, full stop.
> I say GC is a failed experiment because it promised that programmers would be able to write code without worrying about memory.
GC promises that programmers don't have to worry about freeing memory correctly, and it delivers on that promise. I'm not a GC purist--there's lots of criticism to be had for GC, but we don't need point at patently false criticisms.
> The borrow checker is an infantile incarnation of a bigger idea that is finally panning out. Rather than garbage collecting during run-time; garbage collect during compilation using static analysis. Being in its infancy it's not as easy and free to use as we'd like. But it's the path forward.
Maybe. I like the idea, but I'm skeptical that putting constraints on the programmer is going to be an economical solution, at least for so long as the economics favor rapid development over performance. Conceivably rather than rejecting code that aggrieves the borrow checker, we could picture a language that converts those references into garbage collected pointers transparently, but we kind of have this already today via escape analysis--and indeed, I think this is the economic sweet spot for memory management because it lets users have a GC by default but also minimize their allocations for hot paths.
> Hence my comment: "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."
But the borrow checker is strictly less effective in preventing memory leaks than a (tracing) GC (borrow checker will happily allow circular refcounts). More importantly, having to pacify the borrow checker on every single codepath when only 1-2% of code paths are ever going to be problematic is not a good use of your time, especially when you can do some light refactoring to optimize. With respect to GC stalls, these are particularly rare if you have a GC that is tuned to low-latency (Go's GC can free all memory in less than a millisecond in most cases).
> It's not about performance; it's about saving yourself the time of having to come back to your code a month later because your TODO app is using a gig of RAM and randomly hitching.
That sounds like the textbook definition of a performance concern, but again memory usage is orthogonal to GC and random hitching isn't a problem for latency-tuned GCs. Even while Rust is faster than many of its GC counterparts, this difference typically comes down to the ability of the compiler to output optimized code--not the memory management system. That said, for realtime applications, nondeterministic GCs aren't appropriate.
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.
I'm guessing this performance difference isn't caused by GC but rather correlated with GC. I.e., GC langs tend to output relatively poorly-optimized code relative to the absolute beastly C/C++/Rust compilers or else idiomatic code results in objects scattered all over the heap (killing cache coherency) while idiomatic C, C++, Rust, etc tend to allocate coherent objects (objects which tend to be accessed in succession) next to each other in memory.
TL;DR: No doubt a GC can be slower than manually managed memory in some cases, but it's insufficient to conclude that the entire performance gap between C/C++/Rust and Java/Go/etc is attributable to GC.
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?!?
Edit: another thing, compiling to native is not really a first class citizen on .NET. That makes it a bit worse to distribute tools compared to Rust, Go or OCaml. Scala also suffer from this.
VScode F# plugin and Rider also have much more resources into them.
Then 20 years of production code to chose from.
Last time I use the VSCode F# plugin (around a year ago), the experience was strictly worse than rust-analyzer. The compiler errors are also not as good. I've never used Rider so I can't comment on that.
You're right about the 20 years of production code for C#. NuGet lists 241418 packages compared to crates.io 61579 crates, and there's a good chance most of them are more mature than the Rust alternatives. However that's C#, not F#, and I doubt F# represents more than 10% of the packages. That's still better than doing it yourself if there's no package or writing bindings to C though.
I still think F# and Scala are solid choices if you want a functional language today, but it's not the "garbage collected Rust" ideal I wish we had.
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.
I've heard good things about Nim too for this niche but never tried it. I think it'll suffer from the same problem of not being able to leverage an existing ecosystem though.
It is certainly difficult to justify breaking away from the huge established multiple decade ecosystems and standard libraries seen with the JVM/.NET/Python platforms for instance.
Swift is another great language - forever dented by being tied hand and foot to the Apple holy garden and Objective-C legacy and runtime with memory-related keywords such as 'weak' and 'unowned'.
Nim (and perhaps D) are the closest in my mind to the "garbage collected Rust" in that they are not only garbage collected, but they are procedural-oriented, can write highly generic code and macros, and come with near-C performance. Given the "Pythonic Rust" title, another edge Nim has is its semantic whitespace, very Python-esque syntax.
* https://gluon-lang.org/
* https://github.com/PistonDevelopers/dyon
Rust is waiting for that interior language so that everyone doesn't need to subscribe to the same complexity budget.I don't know anything about dyon but a quick look tells me it's more meant for game development.
D and Nim are both good candidates IMO.
Meanwhile, both D and Nim have the benefits of being procedurally grounded, and hence more familiar to someone coming from (say) C# or Java.
Having said that, I think both of those languages may suffer from a lack of tooling/library breadth & depth. Nim in particular seems really cool, but it seems to be struggling to catch enough attention & interest to build a larger community -- probably in large part because it targets many of the same people who are currently high on Rust.
I do agree that D and Nim may be easier to approach from C# or Java, or even Python for Nim or C and C++ for D. These already represent a huge chunk of programmers, but not really what the typical person looking for a "garbage collected Rust" is, in my opinion. Especially since Java and C# programmers already have Scala and F#. While they're both different from what they're used to, they leverage the same plateform and can use the same libraries which is a huge plus.
I agree with your conclusion too, and I think OCaml suffers from this too. Scala and F# have at least the libraries part covered.
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.
I suspect that every language in the world can be clear and direct. I am sure that some people can write unintelligible pseudocode.
We don't expect speakers of other languages to write more Englishonic phrases, although of course that does happen. (English speakers often criticise people for not speaking good English.)
Every language is readable by and intelligible to people who know the language.
Pseudocode is a useful concept. There is no "correct" pseudocode because it is meant as a DSL for _thinking_. Any non-trivial implementation of thinking will quickly become more detailed and more subtle in notation than a shopping list (for example). Opinions about the subtlety of notation abound.
I am not aware of any high-level language that makes a shopping list hard to understand. Above that, we are deeply into opinion about what defines "clutter", "ceremony", and effective notation.
Hmm, what is the "non-political" reality in the question of equality of languages?
> the [Python] language syntax is widely known as a success.
There are other successful languages, too.
Human languages aren't equal; plenty of languages have problems either in specific areas or just generally, and any academic linguist can tell you (off the record) which.
> There are other successful languages, too.
Python is probably the most successful teaching language; I can't think of another language with a better reputation syntax-wise. (And if another language has such a reputation, it's probably because that language is also "Pythonic").
Honestly, I would personally teach plain C for algorithms because it has the simple for loops and while loops, tail-call recursion, arrays and structures.
Python has a kitchen sink.
Not necessarily. Most of what it "shields" users from is unnecessary ceremony and clutter rather than relevant system behaviour.
> Honestly, I would personally teach plain C for algorithms because it has the simple for loops and while loops, tail-call recursion, arrays and structures.
C's loops are not simple, C implementations do not generally have tail calls, C makes the distinction between arrays and pointers far too subtle (which not only confuses learners but also causes bugs in real code), C's structure support is bad (primitive unchecked unions, but no support for proper disjoint sum types). It may have been useful as a portable assembler at one point (back when it was compiled in simple fashion), but it's not a good language for anything these days.
Hmm, once again you allude to unspoken truth. What is your understanding of this unspoken truth about which languages are "better"? I assume that if you hold an opinion, you can present it clearly without vague references to unnamed sources.
> Python is probably the most successful teaching language; I can't think of another language with a better reputation syntax-wise. (And if another language has such a reputation, it's probably because that language is also "Pythonic").
In pseudocode, what you have written is: I assert P because I think P is best and prefer P; also, any other language that meets my requirements is P.
I don't want to get banned.
> In pseudocode, what you have written is: I assert P because I think P is best and prefer P; also, any other language that meets my requirements is P.
Your pseudocode has a type error.
I don't much care for Python myself. But I believe languages with reputations for good syntax are Python-like. If this isn't so, it should be easy to provide a counterexample: a language that has a reputation for a good syntax that isn't Pythonic.
"Only syntax like P has a good reputation". That is your opinion and I uphold your right to hold it. I would however like to understand it better.
Given this dependency on the "reputation" of "pythonic syntax", whom do you accept as "recommenders" for reputation? What constitutes a "good reputation" to your mind?
Do the importance of project, or perhaps durability of code have any value in this reputation?
Is it possible that more detailed notation has a purpose, or is it always "clutter" because it is not "pythonic" or "Englishonic"? Math notation itself is eloquent in the extreme, yet it is not "pythonic" and certainly not "Englishonic".
Is it enough that millions of other people use different tools? Literally billions of other people speak and write a language that does not have the "Englishonic" properties of English, for example. Some of these languages have a notation that is superior to English. [see GB Shaw on English notation]
You say quite clearly in another comment that "C" is not a good language, despite its importance as a language and its influence on several other important, long-serving programming languages. I will just cite the TIOBE index as something tangible; if imperfect, it is at least not a mysterious allusion.
Take one of these languages. Javascript, for example, is a very successful language. Apart from the "ecosystems" of languages, I assume you accept that the notation of Javascript is -- by any measure other than aspersions -- a successful notation system.
Do you actually disagree with me about the reputation of different language syntaxes? I don't have a specific list of influences, just a general impression from e.g. HN-like discussion sites, programming meetups, work colleagues...
> Do the importance of project, or perhaps durability of code have any value in this reputation?
No - we're talking solely about syntax.
> Is it enough that millions of other people use different tools? Literally billions of other people speak and write a language that does not have the "Englishonic" properties of English, for example. Some of these languages have a notation that is superior to English. [see GB Shaw on English notation]
I see your last two sentences as the demonstration that the answer to your question is "no". A language may become very popular despite having a very poor syntax, and even clear improvements to syntax are often not adopted.
> You say quite clearly in another comment that "C" is not a good language, despite its importance as a language and its influence on several other important, long-serving programming languages. I will just cite the TIOBE index as something tangible; if imperfect, it is at least not a mysterious allusion.
Sure, and I'm aware that this is a controversial view. I think few would defend C's syntax; rather they tend to claim that it has good performance or is close-to-the-machine (views that I disagree with, but would acknowledge the popularity of, and be prepared to argue my case against).
> Take one of these languages. Javascript, for example, is a very successful language. Apart from the "ecosystems" of languages, I assume you accept that the notation of Javascript is -- by any measure other than aspersions -- a successful notation system.
I don't accept that a language being popular means it has good syntax, if that's what you're saying.
"Pseudo-code" itself can be anything, as it is a term coined for a loose notation of ideas.
If your objection were "line noise" (i.e. non-Pythonic or non-Englishonic characters), the bias in this is striking. There are other languages that are as effective or even better. The fact that we may not understand these other languages is not an elevated argument for converting them all to a language that we do understand, except perhaps as a study exercise.
As far as English itself is concerned, it is a disastrous confusion of phonemical artefacts. People learn to speak and write English despite the major problems with the writing conventions.
You say "reputation" is your measure, but this is nothing more than "group opinion". You responded that professional popularity is not your measure, so C, Java, and Javascript do not receive your approval. Yet they are successful languages. They are not perfect, but neither is Python.
As far as human languages are concerned, your position is untenable. A fluent speaker speaks $language and understands $language in its subtleties. A person who does not speak $language understands little (or perhaps nothing) and is either trying to learn or has installed opinions instead of knowledge.
One could say the same about e.g. the scientific consensus on a given topic. Ultimately anything nontrivial in today's world relies on other people.
> You responded that professional popularity is not your measure, so C, Java, and Javascript do not receive your approval. Yet they are successful languages.
They are popular but not for their syntax. Their fans and advocates largely admit as much. Plenty of professionals will say things like "I use language X despite its cumbersome syntax, because ...".
> As far as human languages are concerned, your position is untenable. A fluent speaker speaks $language and understands $language in its subtleties. A person who does not speak $language understands little (or perhaps nothing) and is either trying to learn or has installed opinions instead of knowledge.
And yet it's possible to be fluent in multiple languages, and also to study languages in an objective way without being fluent in them. Linguistics is a legitimate field of study with a wide body of existing research (computer language design, on the other hand, has not yet reached that level of maturity).
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.
I started thinking along the lines of an arena allocator, that would allow a shorter lifetime than static so you could remove unused references by dropping the arena and moving over still live references to a new arena. I guess arenas the wrong term with that behaviour, maybe generational mark and sweep garbage collector is closer to describing this approach.
It a avoids the double reference though of the Rc<> model.
https://play.rust-lang.org/?version=stable&mode=debug&editio...
With the same principle, we can use a static, arc and mutex to use a the cache as a global variable. And implement thread-safe string interning. Here, locking the cache at the wrong time during the drop can lead to a race condition.
https://play.rust-lang.org/?version=stable&mode=debug&editio...
To make the InternedStr behaves a bit more like &str or an immutable String, I implemented Clone, Display, Pointer, conversion from &Interned to &str. Ideally it should probably resemble how String de-references to &str for everything (Deref<Target = str>).
Edit: this might be interesting to you: https://docs.rs/crossbeam-epoch/0.9.4/crossbeam_epoch/
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.
It is of course possible to express a shallower copy, but not in the same generic way as a universal trait, that I know of, in any case.
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...
Given Superset struct A, some other struct B that happens to have a subset of A’s fields, and some function foo which takes an argument of type B, you could
1) implement From<A> for B, and use that to convert instances of A when you want to call foo. This would probably involve some copying and/or allocation.
2) back up and turn foo into something that takes a trait argument instead. Now instead of taking instances of A, what it needs struct to provide is defined by a trait, which you can provide implementations of for both A and B. Now you can pass either to foo.
3) potentially, depending on the layout of structs, create a union and do some type punning to convert between them. this requires unsafe and you’d better be right about the struct layouts.
4) just make foo take a tagged union of the two structs. this isn’t unsafe but has different storage tradeoffs. also foo would need to handle each case separately.
5) find some other way to skin this cat. there’s plenty
#2 would be idiomatic in most circumstances I think?
```
struct Person { name: String, }
struct Engineer { name: String, boss: String, }
trait Name { fn get_name(&self) -> &str; }
impl Name for Person { ... }
impl Name for Engineer { ... }
```
It really depends on how you're implementing it. If you're doing a clone/deepcopy-style conversion, or if you're consuming the value you're casting from. However, since most values in Rust are placed on the stack, "allocating" them is incredibly cheap. Moving them around is often also cheap, and involves just a few `mov`s from registers to registers, or stack-address to stack-address.
A very simple example: https://godbolt.org/z/WMePqMd71
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.
I have long felt that retrofitting a language to add support for immutability/FP constructs is better than nothing but significantly worse than starting with immutability as a core principle.
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.