Hacker News new | ask | show | jobs
by joshuamorton 2583 days ago
I disagree with only one thing in this article. Frozenset is super useful. You should prefer frozenset over set by default imo. Immutable objects are safer to work with, often easier to work with (frozenset is hashable, you can key a dict with it), and sets come up all the time in a lot of work. You can get by with a sorted list, but sets are nicer and faster.
4 comments

Great point. I do agree that those who use sets heavily should probably know about frozenset. :)

I've never very rarely seen these used in production code though. I'm also not as strongly biased toward them because set objects in my own code are often pretty short-lived so their mutability rarely matters.

I found myself using them more and more often as I started to adopt type annotations.

As you do that, you start to realize that you don't need a MutableMapping. Just a Mapping will do, much less a Dict. Same with Set.

Troy, if you are reading this: please lower your output a bit. I like your stuff a lot but I had to start filtering out your emails because they were relentless.
> I disagree with only one thing in this article. Frozenset is super useful.

Many of the "don't" callables are useful and I'd say I've used about half (`format` is especially nice as a more flexible version of `str`).

But Python's tendency to mutability and the `set` interface makes frozenset verbose to use & have higher overhead than sets[0]. Usually code is terser and just as clear using sets without mutating them. Which is a shame as of course you lose the safety of enforcing immutability (at runtime but still).

Then again, I guess if you're using a type checker it matters less: it shouldn't let you mutate a `set` if you've typed it as `Set` (rather than `MutableSet`).

[0] IIRC there's only one operation which is specifically optimised for frozensets: copy

I completely agree. Working on complex enterprise Python applications, a pretty significant suite of bugs comes from long-lived, mutable objects. We’ve generally had good luck with preferring immutability wherever possible, both using builtins (tuples rather than lists when possible, frozenset) and custom classes. I just wish frozendict was part of the stdlib!
Ha! That was the thing I was most excited to learn about. I’ve never come across it in any codebases I’ve worked on, but will definitely begin training myself to use it by default over a normal set.