←back to thread

191 points jwilk | 1 comments | | HN request time: 0.206s | source
Show context
pansa2 ◴[] No.46230704[source]
I wonder whether Raymond Hettinger has an opinion on this PEP. A long time ago, he wrote: "freezing dicts is a can of worms and not especially useful".

https://mail.python.org/pipermail/python-dev/2006-February/0...

replies(8): >>46230899 #>>46230957 #>>46231064 #>>46231597 #>>46232170 #>>46234698 #>>46235104 #>>46271495 #
pkulak ◴[] No.46235104[source]
This is why I love how Rust approached this; almost by accident to make borrow checking work. Every reference is either mutable or not, and (with safe code), you can't use an immutable reference to get a mutable reference anywhere down the chain. So you can slowly construct a map through a mutable reference, but then return it out of a function as immutable, and that's the end of it. It's no longer ever mutable, and no key or value is either. There's no need to make a whole new object called FrozenHashMap, and then FrozenList, and FrozenSet, etc. You don't need a StringBuilder because String is mutable, unless you don't want it to be. It's all just part of the language.

Kotlin _kinda_ does this as well, but if you have a reference to an immutable map in Kotlin, you are still free to mutate the values (and even keys!) as much as you like.

replies(3): >>46235897 #>>46236777 #>>46237010 #
vlovich123 ◴[] No.46237010[source]
You cannot return an immutable version. You can return it owned (in which case you can assign/reassign it to a mut variable at any point) or you can take a mut reference and return an immutable reference - but whoever is the owner can almost always access it mutably.
replies(2): >>46237152 #>>46237628 #
tekne ◴[] No.46237628[source]
I mean, if you return an immutable reference, the owner in fact cannot mutate it until that reference is dropped.

If you in fact return e.g. an Rc::new(thing) or Arc::new(thing), that's forever (though of course you can unwrap the last reference!)

replies(1): >>46242985 #
1. aw1621107 ◴[] No.46242985[source]
> I mean, if you return an immutable reference, the owner in fact cannot mutate it until that reference is dropped.

Might be worth noting that "dropped" in this context doesn't necessarily correspond to the reference going out of scope:

    fn get_first(v: &Vec<i32>) -> &i32 {
        &v[0]
    }

    fn main() {
        let mut v = vec![0, 1, 2];
        let first = get_first(&v);
        print!("{}", first});
        v.push(3); // Works!
        // print!("{}", first); // Doesn't work
    }